Using a constructor to set a number back to 1 when it goes over a certain number or below 0

Advertisements

so I am writing a program where when a variable called Floor goes over the topFloor it resets back to 1 or does the same when it goes below 0. I am pretty new to java and just started learning constructors so some help would be appreciated.

Here is my code for the constructor and method:

private final int topFloor = 17;
int goToFloor;
private int floor = 1;

 //change floor to 1 if over or under
    Elevator(int floor){
        this.floor = floor;
         if(floor < 0) {
            floor = 1;
         }
         if (floor > topFloor) {
             floor = 1;
         }
        }

//go to floors.
public void goToFloor(int floor) {
        this.floor = floor;
            if (floor > topFloor) {
                System.out.println("Error, Too High!");
            }
            if (floor < 0) {
                System.out.println("Error, Impossible Floor!");
            }
        }

@Override
    public String toString() {
           String s = " Floor = " + floor;
           return s;
        }

Here is my code to print out the method in a separate class:

Elevator southElevator = new Elevator();
Elevator eastElevator = new Elevator();
 
//go to too big
        southElevator.closeDoor();
        southElevator.goToFloor(92);
        System.out.println(southElevator.toString());
         
        //go to a negative number
        southElevator.goToFloor(-8);
        System.out.println(southElevator.toString());

Here is the output I am getting:

Error, Too High!
Floor = 92
Error, Impossible Floor!
Floor = -8

This is all of my code, I think it probably has something to do with the constructor but I am not sure how to fix it. Any help would be appreciated.

>Solution :

When you change floor in the constructor, you are only changing the value of the floor parameter, not the instance field (this.floor). Set this.floor = floor; in the last line of the constructor, so its value is set according to the modified value of the floor parameter.

For the the goToFloor method, you should perform the reset for each error condition. Only set the value to the parameter value if it is valid. The constructor cannot help with this because the instance has already been created.

if (floor > topFloor) {
    System.out.println("Error, Too High!");
    this.floor = 1; // reset
} else if (floor < 0) {
    System.out.println("Error, Impossible Floor!");
    this.floor = 1; // reset
} else {
    this.floor = floor;
}

Leave a Reply Cancel reply