我必须确定哪些房间较大,我的代码是:
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)); } }
输出:
false false
如你看到的第一个输出是假的,没关系,第二个输出也是假的,但是当我们读取这些代码时,我们可以很容易地看到第二个房间必须是真的.在本练习中,我们应该得到如下输出:
false true
你能解释一下我的错误吗?我可以通过哪些方式获得正确的输出?
你应该改变
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; }
至
public Apartment(int rooms, int squareMeters, int pricePerSquareMeter) { this.room = rooms; // Typo was here. this.squareMeters = squareMeters; this.pricePerSquareMeter = pricePerSquareMeter; }