我的嵌套for循环不执行,我不知道为什么

时间:2014-12-06 11:56:54

标签: java multidimensional-array nested-loops

我的简单嵌套for循环没有执行。这段代码位于一个方法中。方法本身正在执行,并且它周围的代码正在执行,但嵌套循环没有执行。我尝试使用相同的方法在不同的区域中复制和粘贴代码,但它不起作用。我尝试创建一个与此项目无关的不同类,并通过必要的调整将其粘贴到那里,但它不起作用。

所有其他必要变量和数字信息都可在代码和结果中查看。

      System.out.println("This is just to show that variables do have actual numbers in them." +
                       "\n  basePointy =  " + basePointy + "\n  basePointx = " + basePointx + 
                       "\n  boardMatrix.length = " + boardMatrix.length + "\n  boardMatrix[0].length = " + boardMatrix[0].length + 
                       "\n  a[0][0] = " + a[0][0] + "\n  a[5][5] = " + a[5][5] + "\n");

      System.out.println("This is before the nested for loop");

      //This is the problem area.
      for(int yaxisCounter = basePointy + 185; yaxisCounter < boardMatrix.length; yaxisCounter++)
      {
         System.out.println("This is in the first part of the nested for loop");
         for(int xaxisCounter = basePointx + 221; xaxisCounter < boardMatrix[0].length; xaxisCounter++)
         {
            boardMatrix[yaxisCounter-basePointy-185][xaxisCounter-basePointx-221] = a[yaxisCounter][xaxisCounter];    
            System.out.println("This is in the second part of the nested for loop");
         } 
      }
      System.out.println("This is after the nested for loop");

这是我在运行代码后得到的结果。

This is just to show that variables do have actual numbers in them.
  basePointy =  160
  basePointx = 46
  boardMatrix.length = 16
  boardMatrix[0].length = 300
  a[0][0] = -8345659
  a[5][5] = -8412480

This is before the nested for loop

This is after the nested for loop

请注意不打印“这是嵌套for循环的第一部分。”和“这是嵌套for循环的第二部分。”但打印/执行嵌套for循环之前和之后的所有内容。

提前感谢那些阅读和为人们提供帮助的人

3 个答案:

答案 0 :(得分:1)

因为当你开始你的外环时,你的yaxisCounter = 160 + 185 = 345,你的循环条件是yaxisCounter < boardMatrix.length,这是假的,因为16不大于345(即345 <16)

答案 1 :(得分:1)

因为第一个循环条件为假

答案 2 :(得分:0)

试试这个

for (int yaxisCounter = basePointy + 185; yaxisCounter < boardMatrix.length; yaxisCounter++) {
    System.out.println("This is in the first part of the nested for loop");
    for (int xaxisCounter = basePointx + 221; xaxisCounter < boardMatrix[yaxisCounter].length; xaxisCounter++) {
        boardMatrix[yaxisCounter - basePointy - 185][xaxisCounter - basePointx - 221] = a[yaxisCounter][xaxisCounter];
        System.out.println("This is in the second part of the nested for loop");
    }
}