The second conclusion should be true, but it shows false

I have to determine which numbers are larger, and my codes are:

public class Apartment {

    private int room;
    private int squareMeters;
    private int pricePerSquareMeter;

    public Apartment(int rooms, int squareMeters, int pricePerSquareMeter) {
        this.room = room;
        this.squareMeters = squareMeters;
        this.pricePerSquareMeter = pricePerSquareMeter;
    }

    public boolean larger(Apartment otherApartment) {
        if (this.room > otherApartment.room) {
            return true;
        }
        return false;
    }

    public static void main(String[] args) {
        Apartment studioManhattan = new Apartment(1, 16, 5500);
        Apartment twoRoomsBrooklyn = new Apartment(2, 38, 4200);
        Apartment fourAndKitchenBronx = new Apartment(3, 78, 2500);

        System.out.println(studioManhattan.larger(twoRoomsBrooklyn));
        System.out.println(fourAndKitchenBronx.larger(twoRoomsBrooklyn));
    }

}

Output:

false
false

the first conclusion, as you see, is false, this is normal, the second is also incorrect, but when we read these codes, we can easily see that the second room should be true. And in this exercise, we should get the conclusion as follows:

false
true

Can you explain where I am wrong? With what methods can I achieve the correct conclusion?

+4
source share
2 answers

You have to change

public Apartment(int rooms, int squareMeters, int pricePerSquareMeter) {
        this.room = room; // Same as this.room = this.room, no effect at all.
        this.squareMeters = squareMeters;
        this.pricePerSquareMeter = pricePerSquareMeter;
    }

to

public Apartment(int rooms, int squareMeters, int pricePerSquareMeter) {
        this.room = rooms; // Typo was here.
        this.squareMeters = squareMeters;
        this.pricePerSquareMeter = pricePerSquareMeter;
    }
+7
source
this.room = rooms;

Change this line in your constructor. Consider using an IDE, this is a simple typo.

+1
source

Source: https://habr.com/ru/post/1667109/


All Articles