I have to determine which rooms 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
first output as you see is false, it is okay, second one is also false, but when we read these codes, we can easily see that second room must be true. And in this exercise we should get the output as following:
false
true
Can you explain where I mistake? With which ways may I achieve the correct output ?
You should 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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With