Difference between revisions of "Polimorfismo, Interfaces, Classes Abstractas/Exercício 02: Tabelas e Predicados"

From Wiki**3

< Polimorfismo, Interfaces, Classes Abstractas
(Selecção de um número Igual a um dado: EqualTo)
 
(One intermediate revision by the same user not shown)
Line 4: Line 4:
 
Modele e implemente a classe Table que contém um número fixo de inteiros (especificado na altura da criação das suas instâncias). Essa classe possui um método ( contains) que permite verificar se um dos números obedece a um critério de selecção definido por um predicado passado na altura da chamada ao método. Considere que os predicados definem o método ok (que recebe um inteiro e devolve um booleano).
 
Modele e implemente a classe Table que contém um número fixo de inteiros (especificado na altura da criação das suas instâncias). Essa classe possui um método ( contains) que permite verificar se um dos números obedece a um critério de selecção definido por um predicado passado na altura da chamada ao método. Considere que os predicados definem o método ok (que recebe um inteiro e devolve um booleano).
  
<java5>
+
<source lang="java">
 
Table t = new Table(3);  // table with 3 integers
 
Table t = new Table(3);  // table with 3 integers
  
Line 16: Line 16:
  
 
if (t.contains(p2)) System.out.println("YES"); else System.out.println("NO");
 
if (t.contains(p2)) System.out.println("YES"); else System.out.println("NO");
</java5>
+
</source>
  
 
Defina Table, SelectionPredicate, GreaterThan e EqualTo.
 
Defina Table, SelectionPredicate, GreaterThan e EqualTo.
Line 32: Line 32:
  
 
{{CollapsedCode|Ficheiro '''Table.java'''|
 
{{CollapsedCode|Ficheiro '''Table.java'''|
<java5>
+
<source lang="java">
 
/**
 
/**
 
  * A table holding a fixed number of integers.
 
  * A table holding a fixed number of integers.
  *  
+
  *
 
  * It is possible to verify certain predicates against the table's contents.
 
  * It is possible to verify certain predicates against the table's contents.
 
  */
 
  */
 
public class Table {
 
public class Table {
  
/**
+
    /**
* Space for a fixed number of integers.
+
    * Space for a fixed number of integers.
*/
+
    */
int _vector[];
+
    int _vector[];
  
/**
+
    /**
* @param nInts
+
    * @param nInts
*            number of integers to store.
+
    *            number of integers to store.
*/
+
    */
public Table(int nInts) {
+
    public Table(int nInts) {
_vector = new int[nInts];
+
        _vector = new int[nInts];
}
+
    }
  
/**
+
    /**
* FIXME: insert checks to ensure position is within range.
+
    * FIXME: insert checks to ensure position is within range.
*  
+
    *
* @param position
+
    * @param position
*            position to define
+
    *            position to define
* @return value at position
+
    * @return value at position
*/
+
    */
public int getValue(int position) {
+
    public int getValue(int position) {
return _vector[position];
+
        return _vector[position];
}
+
    }
  
/**
+
    /**
* FIXME: insert checks to ensure position is within range.
+
    * FIXME: insert checks to ensure position is within range.
*  
+
    *
* @param position
+
    * @param position
*            position to define
+
    *            position to define
* @param value
+
    * @param value
*            value to set
+
    *            value to set
*/
+
    */
public void setValue(int position, int value) {
+
    public void setValue(int position, int value) {
_vector[position] = value;
+
        _vector[position] = value;
}
+
    }
  
/**
+
    /**
* Set all positions to the same value.
+
    * Set all positions to the same value.
*  
+
    *
* @param value
+
    * @param value
*            value to set
+
    *            value to set
*/
+
    */
public void setAll(int value) {
+
    public void setAll(int value) {
for (int position = 0; position < _vector.length; position++)
+
        for (int position = 0; position < _vector.length; position++)
_vector[position] = value;
+
            _vector[position] = value;
}
+
    }
  
/**
+
    /**
* @param predicate
+
    * @param predicate
*            the predicate to validate.
+
    *            the predicate to validate.
* @return true, if the predicate is valid for at least one position; false,
+
    * @return true, if the predicate is valid for at least one position; false,
*        otherwise.
+
    *        otherwise.
*/
+
    */
public boolean contains(SelectionPredicate predicate) {
+
    public boolean contains(SelectionPredicate predicate) {
for (int position = 0; position < _vector.length; position++)
+
        for (int position = 0; position < _vector.length; position++)
if (predicate.ok(_vector[position])) return true;
+
            if (predicate.ok(_vector[position])) return true;
return false;
+
        return false;
}
+
    }
  
 
}
 
}
</java5>
+
</source>
 
}}
 
}}
  
Line 106: Line 106:
  
 
{{CollapsedCode|Ficheiro '''SelectionPredicate.java'''|
 
{{CollapsedCode|Ficheiro '''SelectionPredicate.java'''|
<java5>
+
<source lang="java">
 
/**
 
/**
 
  * A predicate to be evaluated against a value.
 
  * A predicate to be evaluated against a value.
Line 112: Line 112:
 
public interface SelectionPredicate {
 
public interface SelectionPredicate {
  
/**
+
    /**
* @param value the value to be tested.
+
    * @param value the value to be tested.
* @return true, if the method evaluates true for argument; false,
+
    * @return true, if the method evaluates true for argument; false,
*        otherwise.
+
    *        otherwise.
*/
+
    */
boolean ok(int value);
+
    boolean ok(int value);
  
 
}
 
}
</java5>
+
</source>
 
}}
 
}}
  
 
== Selecção de um número maior que um dado: GreaterThan  ==
 
== Selecção de um número maior que um dado: GreaterThan  ==
  
<java5>
+
{{CollapsedCode|Ficheiro '''GreaterThan.java'''|
 +
<source lang="java">
 
/**
 
/**
 
  * Predicate to test for relative magnitude.
 
  * Predicate to test for relative magnitude.
Line 131: Line 132:
 
public class GreaterThan implements SelectionPredicate {
 
public class GreaterThan implements SelectionPredicate {
  
/**
+
    /**
* The value to test against.
+
    * The value to test against.
*/
+
    */
int _value = 0;
+
    int _value = 0;
+
   
/**
+
    /**
* @param value
+
    * @param value
*/
+
    */
public GreaterThan(int value) {
+
    public GreaterThan(int value) {
_value = value;
+
        _value = value;
}
+
    }
  
/**
+
    /**
* @see SelectionPredicate#ok(int)
+
    * @see SelectionPredicate#ok(int)
*/
+
    */
@Override
+
    @Override
public boolean ok(int value) {
+
    public boolean ok(int value) {
return _value < value;
+
        return _value < value;
}
+
    }
  
 
}
 
}
</java5>
+
</source>
 +
}}
  
 
== Selecção de um número Igual a um dado: EqualTo  ==
 
== Selecção de um número Igual a um dado: EqualTo  ==
  
 
{{CollapsedCode|Ficheiro '''EqualTo.java'''|
 
{{CollapsedCode|Ficheiro '''EqualTo.java'''|
<java5>
+
<source lang="java">
 
/**
 
/**
 
  * Predicate to test for equality.
 
  * Predicate to test for equality.
Line 163: Line 165:
 
public class EqualTo implements SelectionPredicate {
 
public class EqualTo implements SelectionPredicate {
  
/**
+
    /**
* The value to test against.
+
    * The value to test against.
*/
+
    */
int _value = 0;
+
    int _value = 0;
+
   
/**
+
    /**
* @param value
+
    * @param value
*/
+
    */
public EqualTo(int value) {
+
    public EqualTo(int value) {
_value = value;
+
        _value = value;
}
+
    }
  
/**
+
    /**
* @see SelectionPredicate#ok(int)
+
    * @see SelectionPredicate#ok(int)
*/
+
    */
@Override
+
    @Override
public boolean ok(int value) {
+
    public boolean ok(int value) {
return _value == value;
+
        return _value == value;
}
+
    }
  
 
}
 
}
</java5>
+
</source>
 
}}
 
}}
  
Line 192: Line 194:
  
 
{{CollapsedCode|Ficheiro '''Application.java'''|
 
{{CollapsedCode|Ficheiro '''Application.java'''|
<java5>
+
<source lang="java">
 
/**
 
/**
 
  * Sample uses.
 
  * Sample uses.
Line 198: Line 200:
 
public class Application {
 
public class Application {
  
/**
+
    /**
* @param args
+
    * @param args
*/
+
    */
public static void main(String[] args) {
+
    public static void main(String[] args) {
Table t = new Table(3); // table with 3 integers
+
        Table t = new Table(3); // table with 3 integers
  
t.setAll(90);
+
        t.setAll(90);
  
SelectionPredicate p1 = new GreaterThan(9);
+
        SelectionPredicate p1 = new GreaterThan(9);
  
if (t.contains(p1))
+
        if (t.contains(p1))
System.out.println("YES");
+
            System.out.println("YES");
else
+
        else
System.out.println("NO");
+
            System.out.println("NO");
  
SelectionPredicate p2 = new EqualTo(2);
+
        SelectionPredicate p2 = new EqualTo(2);
  
if (t.contains(p2))
+
        if (t.contains(p2))
System.out.println("YES");
+
            System.out.println("YES");
else
+
        else
System.out.println("NO");
+
            System.out.println("NO");
}
+
    }
  
 
}
 
}
</java5>
+
</source>
 
}}
 
}}
  

Latest revision as of 21:16, 8 November 2018

Problema

Modele e implemente a classe Table que contém um número fixo de inteiros (especificado na altura da criação das suas instâncias). Essa classe possui um método ( contains) que permite verificar se um dos números obedece a um critério de selecção definido por um predicado passado na altura da chamada ao método. Considere que os predicados definem o método ok (que recebe um inteiro e devolve um booleano).

Table t = new Table(3);  // table with 3 integers

// inicialização omitida por simplicidade

SelectionPredicate p1 = new GreaterThan(9);

if (t.contains(p1)) System.out.println("YES"); else System.out.println("NO");

SelectionPredicate p2 = new EqualTo(2);

if (t.contains(p2)) System.out.println("YES"); else System.out.println("NO");

Defina Table, SelectionPredicate, GreaterThan e EqualTo.

Solução

UML: Diagrama de Classes

Note that, in this diagram, only the method relevant for this exercise has been included (class Table). Normally, all methods should be included in the class diagram (except for the obvious ones: getters, setters, and so on).

Diagrama de classes

PO-table-predicates.png

Conceito de tabela: Table

Ficheiro Table.java
/**
 * A table holding a fixed number of integers.
 *
 * It is possible to verify certain predicates against the table's contents.
 */
public class Table {

    /**
     * Space for a fixed number of integers.
     */
    int _vector[];

    /**
     * @param nInts
     *            number of integers to store.
     */
    public Table(int nInts) {
        _vector = new int[nInts];
    }

    /**
     * FIXME: insert checks to ensure position is within range.
     *
     * @param position
     *            position to define
     * @return value at position
     */
    public int getValue(int position) {
        return _vector[position];
    }

    /**
     * FIXME: insert checks to ensure position is within range.
     *
     * @param position
     *            position to define
     * @param value
     *            value to set
     */
    public void setValue(int position, int value) {
        _vector[position] = value;
    }

    /**
     * Set all positions to the same value.
     *
     * @param value
     *            value to set
     */
    public void setAll(int value) {
        for (int position = 0; position < _vector.length; position++)
            _vector[position] = value;
    }

    /**
     * @param predicate
     *            the predicate to validate.
     * @return true, if the predicate is valid for at least one position; false,
     *         otherwise.
     */
    public boolean contains(SelectionPredicate predicate) {
        for (int position = 0; position < _vector.length; position++)
            if (predicate.ok(_vector[position])) return true;
        return false;
    }

}

Conceito de predicado de selecção: SelectionPredicate

Ficheiro SelectionPredicate.java
/**
 * A predicate to be evaluated against a value.
 */
public interface SelectionPredicate {

    /**
     * @param value the value to be tested.
     * @return true, if the method evaluates true for argument; false,
     *         otherwise.
     */
    boolean ok(int value);

}

Selecção de um número maior que um dado: GreaterThan

Ficheiro GreaterThan.java
/**
 * Predicate to test for relative magnitude.
 */
public class GreaterThan implements SelectionPredicate {

    /**
     * The value to test against.
     */
    int _value = 0;
    
    /**
     * @param value
     */
    public GreaterThan(int value) {
        _value = value;
    }

    /**
     * @see SelectionPredicate#ok(int)
     */
    @Override
    public boolean ok(int value) {
        return _value < value;
    }

}

Selecção de um número Igual a um dado: EqualTo

Ficheiro EqualTo.java
/**
 * Predicate to test for equality.
 */
public class EqualTo implements SelectionPredicate {

    /**
     * The value to test against.
     */
    int _value = 0;
    
    /**
     * @param value
     */
    public EqualTo(int value) {
        _value = value;
    }

    /**
     * @see SelectionPredicate#ok(int)
     */
    @Override
    public boolean ok(int value) {
        return _value == value;
    }

}

Programa Principal

O programa principal é como indicado no enunciado do problema e indicado abaixo por motivos de clarificação:

Ficheiro Application.java
/**
 * Sample uses.
 */
public class Application {

    /**
     * @param args
     */
    public static void main(String[] args) {
        Table t = new Table(3); // table with 3 integers

        t.setAll(90);

        SelectionPredicate p1 = new GreaterThan(9);

        if (t.contains(p1))
            System.out.println("YES");
        else
            System.out.println("NO");

        SelectionPredicate p2 = new EqualTo(2);

        if (t.contains(p2))
            System.out.println("YES");
        else
            System.out.println("NO");
    }

}

Compiling and Running

How to Compile?

The compilation is as follows:

 javac Table.java
 javac SelectionPredicate.java
 javac GreaterThan.java
 javac EqualTo.java
 javac Application.java

In fact, compiling Application.java would cause the rest of them be compiled as well (the Java compiler accounts for all explicit class dependencies).

Running

The program starts at a main function (in this case, contained in the Application class):

 java Application