0
I wanted to know how do I add a new value to length and width through setLength and Setwidth, and this value goes through validation ((x > 0 && x < 20)? x : 0):
public class Rectangle {
private double length;
private double width;
//Construtor
public Rectangle(){
this(1.0,1.0);
}
public Rectangle(double l){
this(l,1.0);
}
public Rectangle(double l, double w){
setValues(l, w);
}
//Set and verify values
public void setValues(double l, double w){
setLength(l);
setWidth(w);
}
public void setLength(double l){
length = ((l > 0 && l < 20) ? l : 0);
}
public void setWidth(double w){
width = ((w > 0 && w < 20) ? w : 0);
}
//Get
public double getLength(){
return length;
}
public double getWidth(){
return width;
}
//Calc perimeter
public double calcPerimeter(double l, double w){
return (l+w)*2;
}
//Calc area
public double calcArea(double l, double w){
return (l*w);
}
}
In my test it goes straight through the IF on set:
import java.util.Scanner;
public class RectangleTest {
public static void main(String[] args) {
//Teste do Construtor sobrecarregado
Rectangle myRectangle1 = new Rectangle();
Rectangle myRectangle2 = new Rectangle(2.0);
Rectangle myRectangle3 = new Rectangle(2.0, 3.0);
Rectangle myRectangle4 = new Rectangle(21.0, 3.0);
System.out.printf("Sem argumentos: %.1f\n", myRectangle1.getLength());
System.out.printf("Sem argumentos: %.1f \n\n", myRectangle1.getWidth());
System.out.printf("Com um argumento: %.1f \n", myRectangle2.getLength());
System.out.printf("Com um argumento: %.1f \n\n", myRectangle2.getWidth());
System.out.printf("Com dois argumentos: %.1f \n", myRectangle3.getLength());
System.out.printf("Com dois argumentos: %.1f \n\n",myRectangle3.getWidth());
System.out.printf("Com número maior que 20: %.1f \n",
myRectangle4.getLength());
System.out.printf("Com dois argumentos: %.1f \n\n",
myRectangle4.getWidth());
//Fim do teste de construtor sobrecarregado
Rectangle myRectangle = new Rectangle(1.0 , 1.0); //Define valor inicial
como 1.0
Scanner input = new Scanner(System.in);
double length;
double width;
System.out.print("\nComprimento: "); //Solicita o valor de Length
length = input.nextDouble();
myRectangle.setLength(length);//Determina o novo valor de Length
System.out.print("Largura: "); //Solicita o valor de Width
width = input.nextDouble();
myRectangle.setWidth(width); //Determina o novo valor de Width
System.out.printf("Perímetro: %.1f \t",
myRectangle.calcPerimeter(length, width)); //Calcula o perímetro e exibe
System.out.printf("Área: %.1f \n\n", myRectangle.calcArea(length,
width)); //Calcula a área e exibe o resultado
}
}
I don’t understand, the code doesn’t have
if
. Where there is a condition everything seems ok. If you have any problem, we do not know which, how to reproduce.– Maniero