当前位置:  开发笔记 > 编程语言 > 正文

第二个输出必须为true,但显示为false

如何解决《第二个输出必须为true,但显示为false》经验,为你挑选了1个好方法。

我必须确定哪些房间较大,我的代码是:

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

你能解释一下我的错误吗?我可以通过哪些方式获得正确的输出?



1> C. L...:

你应该改变

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;
    }

推荐阅读
ar_wen2402851455
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有