Java variable that only accept a specific range of values

AllanJ :

I'm new to this so please bear with me. I have homework and I don't really understand what exactly the teacher means by this.

The class name is Elevator

level stores the current level. level is an instance-variable of type int

Limit the number of levels from -2 to 10.

Then create a method called goTo(Level: int).(will send messages)

By limiting to a specific range I guess he means by using a if-statement? If I'm right do I add it in the method below because I can't create if statements directly in the class.

And also why is the method where(): int supposed to return level. It is never used...

public class Elevator {

    int level = 0;

    public void goTo(int level){

        if (level < this.level){
            System.out.println("Elevator going up to floor " + level);
        }
        else if (level > this.level){
            System.out.println("Elevator going  down to floor " + level);
        }
        else if (level == this.level){
            System.out.println("Elevator already on the floor " + level);
        }

    }

    public int where(){
        return level;
    }
}
Rafał Sokalski :

From my point of view that limit should be an if statement in goTo method to prevent sending level different than -2 to 10. So it should looks e.g like that:

public class Elevator {

    int actualLevel = 0;

    public void goTo(int level) {
        if (level < -2 || level > 10) {
            System.out.println("Invalid level!. Levels range is -2 to 10.");
            return;
        }

        if (level > actualLevel) {
            System.out.println("Elevator going up to floor " + level);
            this.actualLevel = level;
        } else if (level < actualLevel) {
            System.out.println("Elevator going  down to floor " + level);
            this.actualLevel = level;
        } else if (level == actualLevel) {
            System.out.println("Elevator already on the floor " + level);
        }
    }

    public int where() {
        return this.actualLevel;
    }

}

Also I made changes in your class variable name because there was mistake in checking if elevetator goes up or down because you mistake method and class variables. And one more thing that if the elevator goes up or down you should assign it to your class variable to hold actual floor.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=307473&siteId=1