-5

I have a project in which I'm working on a class that has mutator and accessor methods. For my mutator methods, I have to return a boolean. "True - indicating the height is within range and that the Object's value has been modified." False, obviously, if it isn't. Height being in range means it's between 1-10 inclusive.

I know how to write a boolean, but how would I do that inside a mutator method? Usually, and keep in mind I'm very new, I would write something along the following:

public void setHeight(int newHeight){
    height = newHeight;
}

How would I place my boolean inside of the mutator method, as well as ensure that the height is within its proper range? My boolean would be something along the lines of:

if (height >= 1 && height <= 10) {
    System.out.println("It's perfect!");
} else {
    System.out.println("Not right!");
}
MercyBeaucou
  • 260
  • 3
  • 13
J. Nav
  • 55
  • 1
  • 8

3 Answers3

0

You need to create an if statement that checks if the height is valid:

public boolean setHeight(int height){

    if(1 <= height && 10 >= height){

        this.height = height;
        return true;

    }

    return false;

}

No else statement is needed because the method ends when return true; is run, and thus anything after the if will not be executed if height is valid.

this.height refers to the height variable of the Object, whereas height in this case refers to the variable defined by the parameter.

MercyBeaucou
  • 260
  • 3
  • 13
-1
public boolean setHeight(int newHeight){
  if (height >= 10) {
    height = newHeight;
    System.out.println("It's perfect!");
    return true;
  }
System.out.println("Not right!");
return false;
}
NimChimpsky
  • 43,542
  • 55
  • 186
  • 295
  • Thanks for the help! I tried looking in the books and everything, but I couldn't find what I needed: the public boolean setHeight – J. Nav Nov 07 '16 at 03:44
-1

You'll have to change the return type of your setter:

public boolean setHeight(int newHeight) {
    if (1<=height && height<=10) {
        height = newHeight;
        return true;
    } else {
        return false;
    }
}
apt1002
  • 799
  • 3
  • 13
  • That makes a lot more sense than what I was doing. So whenever I want to have a boolean inside of a mutator method, I write "public bool" or "public boolean" and then have the usual mutator method? – J. Nav Nov 07 '16 at 03:38
  • Yup. Thanks for spotting the bool -> boolean error. – apt1002 Nov 07 '16 at 03:42
  • Hey, how would you do this for a tester class? I've been struggling for the past hour. I have to use the boolean value for the mutator method. So for something like myWhatever.setHeight..... what? Do you have any recommendations or links? – J. Nav Nov 07 '16 at 05:01
  • You don't even need the else statement, you could just have `return false` at the end. – MercyBeaucou Nov 07 '16 at 05:21