Java while循环为false

时间:2014-09-28 21:46:14

标签: java while-loop

我创建了一个while循环,当它变为真时我想停止

所以我说:

while(!vending1.cansEmpty()) {
    vending1.clickCan();
    count++; 
}

现在它被设置为自动售货机里面有10个罐子 每次你调用方法clickCan(),它减去1可以, 但是当机器为空时(方法变为真),while循环不会结束,它只是无限地继续 我不知道为什么,但

1 个答案:

答案 0 :(得分:0)

public class VendingMachine(){
    private Integer cans;

    public VendingMachine(int numCans) {
        this.cans = numCans
    }

    public void clickCan() {
        cans--;
    }
    public boolean cansEmpty() {
        if (cans <= 0) {
           return true;
        } else {
           return false;
        }
    }
}

我认为你只需要确保你的cans empty函数返回一个布尔值。