Search code examples
javaif-statementsetterbluej

There is something wrong with the if-statement in our setter


We are making a setter with the if-statement. We are trying to limit the approved values, and are using a print-method to print out the value that is set, or "wrong" if the value is not accepted.

This is the method:

Public class Sykkel extends Kjøretøy
{

private int height;


public Sykkel(String colour)
{
    // initialise instance variables
    super(1, colour);
    this.height = height;
}

public void setHeight (int height) {
    if(height > 35 && height < 70){
        System.out.println("Sykkelen er " + height + " cm høy.");
    } else {
        System.out.println("Wrong");
    }
}

public int getHeight() {
    return height;
}

No matter what we set as the height it prints out "Wrong". Does anyone see the error in the code?

we've tried both this.height and just height, but the outcome is still the same.

Thanks in advance.


Solution

  • My observations.

    Your constructor should be:

    public Sykkel(String colour, int height)
    {
        // initialise instance variables
        super(1, colour);
        this.height = height;
    }
    

    In your setHeight method, you need to assign the height to the instance variable.

    public void setHeight (int height) {
        if(height > 35 && height < 70){
            System.out.println("Sykkelen er " + height + " cm høy.");
        } else {
            System.out.println("Wrong");
        }
        // add the below line:
        this.height = height;
    }
    

    The other method seems okay.

    When I call setHeight(40);, I am getting

    Sykkelen er 40 cm høy.
    

    Hope this helps!