【问题标题】:Java for and while loops do no work as expectedJava for 和 while 循环没有按预期工作
【发布时间】:2014-01-19 13:43:24
【问题描述】:

这段代码(Java)不起作用,我不知道为什么。

int[][] arr = {{0, 0, 0}, {0, 1, 0}, {0, 0, 0}};

for(int a = 0; a < arr.length; a++) {
   for(int b = 0; b < arr[a].length;) {
      int c = 1;
      if (arr[a][b] == 0) {
         while((arr[a][(b+c)] == 0) && ((b+c)!=(arr[a].length-1))) {
            c++;
         }
         addBar(b, a, c); // Use these values in another function...
         b = b + c;
      } else {
         b++;
      }
   }
}

问题:b &lt; arr[a].length; 没有得到尊重并再次循环。我做错了什么?

【问题讨论】:

  • while in a loop in a loop
  • 使用调试器看看会发生什么。

标签: java arrays for-loop while-loop


【解决方案1】:

你这样称呼:

while ((arr[a][(b + c)] == 0) && ((b + c) != (arr[a].length - 1)))

里面隐藏着arr[a][(b + c)],c总是等于1。 所以你的 b == 2 在最后一个 for 循环开始时,一切都很好,它进入循环,你正在访问 b+c 元素(2+1),但内部数组中只有 3 个元素,最大索引不应大于 2!

这是你的错误。第一个循环:

  int c = 1;//b==0
  if (arr[a][b] == 0) {//arr[0][0] - correct
     while((arr[a][(b+c)] == 0) && ((b+c)!=(arr[a].length-1))) {
        c++; //c == 2
     }
     addBar(b, a, c); // Use these values in another function...
     b = b + c; //b == 0 + 2 == 2
  } else {
     b++;
  }

第二次循环:

  int c = 1;//b== 2
  if (arr[a][b] == 0) {//arr[0][2] - correct
     while((arr[a][(b+c)] == 0) //ERROR!!! b+c == 3!!!

【讨论】:

    【解决方案2】:

    看看你的第二个 for 循环

    for(int b = 0; b &lt; arr[a].length;) {

    你应该这样做

    for(int b = 0; b &lt; arr[a].length; b++) { - 你忘了 b++

    【讨论】:

    • 我在 for 循环末尾附近手动增加 b,因为可能需要增加 c,这就是 if() 的用途。
    【解决方案3】:
    for(int b = 0; b < arr[a].length; /*you're not incrementing b*/)
    

    所以 b 将永远为 0。将其更改为:

    for(int b = 0; b < arr[a].length; b++)
    

    【讨论】:

    • 我在 for 循环末尾附近手动增加 b,因为可能需要增加 c,这就是 if() 的用途。
    【解决方案4】:

    b+c 退出数组

    if(b+c<arr[a].length)
          {
               while((arr[a][(b+c)] == 0) && ((b+c)!=(arr[a].length-1))) 
               {        
                   c++;
           }
          } 
    

    我认为你想在 while 循环的条件下这样做

    ((b+c)!=(arr[a].length-1)))
    

    但这并不意味着。你仍然可以不在数组中。

    而且你也忘记了其他人提到的 for 循环中的 ++b 增量。

    【讨论】:

      猜你喜欢
      • 2013-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多