J. Nav J. Nav - 1 month ago 10
Java Question

Boolean in Mutator Method

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 height if it sets to a parameter value". False, obviously, if it doesn't. Height being in range means if it fits being 1-10, or so.

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 much 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!");
}

Answer

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;
    }
}