1

I'm not really sure how to validate the info of an object's arguments(parameters? if someone can also explain the difference, that would be great!). So basically, the default values of the variables need to be 1.0 but when I run anything below 1.0, it doesn't take into consideration the if statements that I have put up. For example, the negative values stay negative.How can I make it so that if anything is below 1.0, it must be set to 1.0? Thank you!

private double length;
private double width;
private double height;

public Box(double l, double w, double h){
    length=l;
    if(l<1.0)
        l=1.0;
    width=w;
    if(w<1.0)
        w=1.0;
    height=h;
    if(h<1.0)
        h=1.0;
}
public void setLength(double l){
    if(l<1.0)
        l=1.0;
}
public void setWidth(double w){
    if(w<1.0)
        w=1.0;
}
public void setHeight(double h){
    if(h<1.0)
        h=1.0;
}

Here is the main

Box box3= new Box(7,8,9);
Box box4= new Box(-1.0,-2.0,-3.0);
ben
  • 97
  • 1
  • 1
  • 10
  • 1
    Difference between args and params: http://stackoverflow.com/questions/427653/arguments-or-parameters – Nico Dec 05 '14 at 19:57

1 Answers1

4

You are setting the local variables instead of the members, which have different names :

private double length;
private double width;
private double height;

For example, here's a fix to your constructor :

public Box(double l, double w, double h){
    length=l;
    if(l<1.0)
        length=1.0;
    width=w;
    if(w<1.0)
        width=1.0;
    height=h;
    if(h<1.0)
        height=1.0;
}

Your setters are even worse, as they currently do nothing. Fix them by assigning the input value to the instance member :

public void setHeight(double h){
    height = h;
    if(h<1.0)
        height=1.0;
}
Eran
  • 387,369
  • 54
  • 702
  • 768
  • You can also use this. to make sure you are changing the fields of an object. In the if check: this.length=1.0; – Code Whisperer Dec 05 '14 at 19:59
  • @Eran wow I'm terrible..sorry still new to this. I actually changed both l's to length and so I gave up after that. Thank you tho! – ben Dec 05 '14 at 20:19