gpt4 book ai didi

java - 嵌套 For 循环终止后递增

转载 作者:行者123 更新时间:2023-12-01 18:35:16 25 4
gpt4 key购买 nike

我有 2 个 for 循环,一个嵌套在另一个循环内。它们循环遍历按钮的 2D 数组,以获取使用操作监听器单击的每个按钮的源。

找到按钮后,我将按钮的位置/数组索引传递给外部方法。然而,当从按钮数组中找到按钮时,第一个 for 循环将其终止条件评估为 FALSE,但仍增加 i 的值。导致一关错误。我的代码位于标准操作执行方法中,其中“事件”是 ActionEvent。 Buttons[][] 是一个定义为实例变量的 JButton 数组。它的大小为 10 x 10,并且已添加到面板中。

int i = 0; //this will loop through the columns in the array
int j = 0; //loop through the rows
boolean locatedSource = false; //allows me to escape both loops

for(i = 0; !(locatedSource) && i < buttons.length; i++) //problem here, when i < buttons.length is FALSE i still gets incremented, leading to an off by one error
{
for(j = 0; !(locatedSource) && j < buttons.length; j++)
{
if(event.getSource() == buttons[i][j])
{
locatedSource = true;
break;
}
}
}
//do stuff with i and j in another method. Leads to array out of bounds error / off by one error
}

我应该提到,我不打算通过使用标签来解决这个问题,他们似乎不鼓励。

最佳答案

问题说明

for 循环的增量表达式在每次循环迭代之后执行,而不是之前。请参阅 Oracle Java tutorial 中的以下引用:

for 语句提供了一种迭代一系列值的紧凑方法。程序员通常将其称为“for 循环”,因为它会重复循环直到满足特定条件。 for语句的一般形式可以表示如下:

for (initialization; termination;
increment) {
statement(s)
}

使用此版本的 for 语句时,请记住:

  1. 初始化表达式初始化循环;它在循环开始时执行一次。
  2. 当终止表达式的计算结果为 false 时,循环终止。
  3. 每次循环迭代后都会调用增量表达式;该表达式递增或递减一个值是完全可以接受的。

For循环解决方案

您可以重写循环,使增量成为循环内的第一个语句。

    for (i = 0; !(locatedSource) && i < buttons.length;) {
i++;
for (j = 0; !(locatedSource) && j < buttons.length;) {
j++;
if (event.getSource() == buttons[i][j]) {
locatedSource = true;
}
}
}

While循环版本

鉴于循环变量都是在循环外部初始化的,并且您不想使用 for 循环增量表达式,因此重写代码以使用 while 循环可能会更清楚,如下所示:

    while (!(locatedSource) && i < buttons.length) {
i++;
while (!(locatedSource) && j < buttons.length) {
j++;
if (event.getSource() == buttons[i][j]) {
locatedSource = true;
}
}
}

关于java - 嵌套 For 循环终止后递增,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22284099/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com