Java中嵌套的for循环的执行顺序

时间:2018-09-17 20:02:17

标签: java multidimensional-array nested order-of-execution

找到有效的解决方案后,我试图了解为什么我的解决方案不起作用。我添加了最小的工作示例(MWE),首先显示了有效的解决方案,然后在1和2展示了尝试的解决方案。我手动打印数组的所有元素,然后再次打印for循环。

由此得出的结论是,首先评估外部for循环(带有计数器i),然后再评估内部for循环(带有计数器q)。我很困惑,想知道我对Java for循环评估顺序的理解是不正确的,还是我缺少语法/其他错误。

问题:有人可以提出for循环评估顺序的原因吗?

public class LearnMultiDimensionalArrayLength {

    public static void main(String[] args) {
        // Generate array
        double[][] a = {{1.5, -10.3, 0}, {-2.5, 8, 1.3}};
        // call method that loops through the array
        forloops(a);
    }

    public static void forloops(double[][] a) {
        // Working solution:
        //loops through all elements of the array and prints their values.
        for (double[] x : a)
        {
           for (double y : x)
           {
                System.out.print(y + " ");
           }
           System.out.println();
        }

        // Now I tried my own solution:
        System.out.println("The first dimension length: "+ a.length + 
            " The second dim. length: " + a[1].length);
        System.out.println("first dim-1 ="+  (a.length -1));
        System.out.println("Second dim-1 ="+  (a[1].length -1));

        // Question to self: Why is the following for loop wrong?
        // for (int i=0;i <= a.length;i++){
        //   for (int q=0;q <= a[1].length;i++){
        //     System.out.println("["+i+"]"+"["+q+"]"+"="+a[i][q]);
        //   }
        // }

        // 1. Attempted Answer: Because the lengths are the nr of rows 
        // and nr of columns in the matrix. so with n = 2, there are only the elements
        // 0 and 1 in the first []
        // Test hypotheses by looping through the array a with length-1:

        // for (int i=0;i <= a.length-1;i++){
        //   for (int q=0;q <= a[1].length-1;i++){
        //     System.out.println("["+i+"]"+"["+q+"]"+"="+a[i][q]);
        //   }
        // }

        // Conclusion, that did solve the problem. 
        // 2. Attempt: Print all elements and their values, then compare
        // with what the for loop does:

        System.out.println("a[0][0]="+a[0][0]);
        System.out.println("a[0][1]="+a[0][1]);
        System.out.println("a[0][2]="+a[0][2]);
        System.out.println("a[1][0]="+a[1][0]);
        System.out.println("a[1][1]="+a[1][1]);
        System.out.println("a[1][2]="+a[1][2]);
        // System.out.println("a[2][0]="+a[2][0]);
        // System.out.println("a[2][1]="+a[2][1]);
        // System.out.println("a[2][2]="+a[2][2]);

        // 2.a Troubleshooting: verify the upper bound of the for loops
        // are not producing an error due to differences in types:
        System.out.println(((Object)1).getClass().getName());
        System.out.println(((Object)a[1].length).getClass().getName());
        System.out.println(((Object)(a[1].length-1)).getClass().getName());

       // All expressions are evaluated as integer, both i and q are integers
       // hence the different types should not result in a false negative.

        // The actual problematic for loop:
        System.out.println("Boolean evaluation:" + (1 == (a.length-1)));
        for (int i=0; (i <= (a.length-1));i++){
            for (int q=0; (q <= (a[1].length-1));i++){
                //System.out.println("retry" + "[i="+i+"]"+"[q="+q+"]"+"="+a[i][q]);
                System.out.println("This is the wrong order of for loops" + "[q="+q+"]"+"[i="+i+"]"+"="+a[q][i]);
            }
        }
    }
}

2 个答案:

答案 0 :(得分:0)

为什么不运行这段代码并尝试了解其工作原理...一旦完成,就试一试(更改值),看看会发生什么情况

public static void main(String arg[]) {
  for(int i=0;i<10;i++) {
    System.out.println("Inside the Fist loop "+i);
    for(int j=0;j<10;j++) {
      System.out.println("Inside the second loop "+j);
    }
  }
}

答案 1 :(得分:0)

感谢您的快速响应,正如@azurefrog指出的那样,我在q的计数器中有一个复制粘贴错误,因此,它不断增加内循环的i,从而在行/上产生超出范围的错误/外循环应循环通过的列。

这包含已更正的代码(由于第二行for-loop中的行和列具有不同的长度,并且像原始问题一样被反转,因此在第二个public class SolvedMultiDimensionalArrayLength { public static void main(String[] args) { // Generate array double[][] a = {{1.5, -10.3, 0}, {-2.5, 8, 1.3}}; // call method that loops through the array forloops(a); } public static void forloops(double[][] a) { // Reversed with the intended order: for (int i=0; (i <= (a.length-1));i++){ for (int q=0; (q <= (a[1].length-1));q++){ System.out.println("retry" + "[i="+i+"]"+"[q="+q+"]"+"="+a[i][q]); //System.out.println("This is the wrong order of for loops" + "[q="+q+"]"+"[i="+i+"]"+"="+a[q][i]); } } // The actual solution for loop: for (int i=0; (i <= (a.length-1));i++){ for (int q=0; (q <= (a[1].length-1));q++){ //System.out.println("retry" + "[i="+i+"]"+"[q="+q+"]"+"="+a[i][q]); System.out.println("This was the reversed order, with corrected counter" + "[q="+q+"]"+"[i="+i+"]"+"="+a[q][i]); //error here, since a.length is shorter than a[1].length, and the columns and rows are reversed. } } } } 中出现越界错误)。我很抱歉。

import pandas as pd
solution = pd.date_range(start=date_min , end=date_max, freq='1H')
print(solution)    
DatetimeIndex(['2018-09-16 00:00:00', '2018-09-16 01:00:00',
                   '2018-09-16 02:00:00', '2018-09-16 03:00:00',
                   '2018-09-16 04:00:00', '2018-09-16 05:00:00',
                   '2018-09-16 06:00:00', '2018-09-16 07:00:00',
                   '2018-09-16 08:00:00', '2018-09-16 09:00:00',
                   '2018-09-16 10:00:00', '2018-09-16 11:00:00',
                   '2018-09-16 12:00:00', '2018-09-16 13:00:00',
                   '2018-09-16 14:00:00', '2018-09-16 15:00:00',
                   '2018-09-16 16:00:00', '2018-09-16 17:00:00',
                   '2018-09-16 18:00:00', '2018-09-16 19:00:00',
                   '2018-09-16 20:00:00', '2018-09-16 21:00:00',
                   '2018-09-16 22:00:00', '2018-09-16 23:00:00',
                   '2018-09-17 00:00:00'],
                  dtype='datetime64[ns]', freq='H')