【问题标题】:What should I write in the brackets of this array?我应该在这个数组的括号中写什么?
【发布时间】:2018-04-23 01:51:51
【问题描述】:

在我的构造函数中,我将气泡数组设置为参数中输入的大小。例如,如果用户为“numberOfBubbles”输入“9”,则会创建一个包含 9 个气泡对象的数组。

private double canvasWidth;
private double canvasHeight;
private Bubble[] bubbles;
int count;

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

public void moveAllAndBounce() {


    for( int p = 0; p < count; p++ ){

           bubbles[].moveIt(); 

        }

}

在我的名为“moveAllAndBounce”的方法中,我想在一个 for 循环中在屏幕上移动这 9 个气泡对象,该循环将在 P = 1000 时结束,但是我不知道在括号 [] 中输入什么来完成这个工作,因为数组的大小是在构造函数的参数中启动的。如果我写“bubbles[p]”这将不起作用,因为如果我希望在构造函数中数组的大小为 9,那么一旦 p = 9,循环将停止。我在括号中写什么才能使这项工作?

【问题讨论】:

标签: java arrays loops methods parameters


【解决方案1】:

您的气泡已编号。第一个循环清楚地表明该编号介于 0 和 numberOfBubbles-1 之间;

0, 1, 2, ..., numberOfBubbles-3, numberOfBubbles-2, numberOfBubbles-1

所以,如果你想在第 5 个气泡中调用 moveIt(),那就是索引 4,你会写

bubbles[4].moveIt();

如果您需要移动所有气泡,我建议在每个气泡上单独使用一个循环到moveIt()

【讨论】:

  • 但是如果用户在构造函数中输入一个包含 100 个气泡对象的数组呢?在该方法中,我是否必须手动将每个气泡 [] 写入最多 99 个?
  • @Matt.C 您已经在示例中使用循环来构造气泡。因此,您已经在代码中找到了该问题的答案。
【解决方案2】:

如果你想将每个气泡移动 1000 次,你可以这样写:

public void moveAllAndBounce() {
for( int p = 0; p < count; p++ ){
    for(int i=0; i<numberOfBubbles; i++){
       bubbles[i].moveIt(); 
    }
  }
}

如果你想总共调用 1000 个 moveIt() 函数,那么首先你必须将 count 更改为 count/numberOfBubbles

【讨论】:

  • 我希望它这么简单,但是 numberOfBubbles 不是全局变量,它只是用于构造函数的参数。
  • 没问题,你也可以修改你的moveAllAndBounce函数,把numberOfBubbles和cout传给它。 moveAllAndBounce(Int count, Int numberOfBubbles){...};
【解决方案3】:

所有数组都有一个名为length的变量,arr.length可以访问它。

在您的情况下,您必须构建两个循环:一个用于气泡,一个用于移动。

应该是这样的:

public void moveAllAndBounce(){
  for (int i = 0; i < bubbles.length; i ++)
    for(int p = 0; p < count; p ++)
      bubbles[i].moveIt();
}

【讨论】:

  • 你也可以使用for-each循环:for(Bubble bubble : bubbles){ [...] }
【解决方案4】:

我建议使用 for-each-loop,它在内部转换为常规的 for-loop,编译器负责检查数组或集合的大小(实现 Iterable)。

public void moveAllAndBounce() {
  for (Bubble bubble : bubbles)
    for(int p=0; p<count; p++)
      bubble.moveIt(); 
}

【讨论】:

  • omggg 我爱你,我花了大约 3 天的时间来解决这个问题,你的解决方案奏效了!
  • np,如果它帮助您解决了问题,请接受答案并投票!
猜你喜欢
  • 2020-05-20
  • 2021-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多