【问题标题】:How to use an array in an IF statement?如何在 IF 语句中使用数组?
【发布时间】:2018-04-24 17:54:02
【问题描述】:

我创建了这个程序,其中将在构造函数中创建一组气泡对象,然后气泡将漂浮在画布上,一旦气泡相互接触,它们就会消失并显示“POP!”字样。如果所有气泡都已弹出,则我的名为 noneLeft() 的方法应返回 true,然后将调用另一个名为 redisplayAll() 的方法,并且气泡将重置并再次重新显示。但是,我不确定在弹出最后一个气泡后要为 if 语句返回 true 写什么。如果数组中的最后一个气泡已经弹出,我如何写下来,然后返回 true。我必须使用 bubbles.length 吗?

public Mover(double width, double height, int numberOfBubbles) {
    canvasWidth = width;
    canvasHeight = height;
    bubbles = new Bubble[numberOfBubbles];

    for (int i = 0; i < numberOfBubbles; i ++){

        bubbles[i] = new Bubble();
        bubbles[i].showBubble(width, height);

    }

    count = 0;
}



public boolean noneLeft() {


   if (bubbles[].isPopped() == true){

       return true;

   }

   return false;    

}

【问题讨论】:

  • return Arrays.stream(bubbles).allMatch(x -&gt; x.isPopped());

标签: java arrays loops if-statement bluej


【解决方案1】:

代码应该是

public boolean noneLeft() {
    for (Bubble b : bubbles) {
        if (!b.isPopped()) {
            return false;
        }
    }
    return true;
}

遍历气泡,一旦你找到一个没有弹出的气泡就返回 false,因为至少还剩下一个气泡。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-06
    • 1970-01-01
    • 2018-12-26
    • 2022-01-14
    • 2015-09-06
    • 1970-01-01
    • 2016-07-26
    • 2017-08-30
    相关资源
    最近更新 更多