哪个For循环将首先执行,然后首先完成?

时间:2020-03-14 23:29:44

标签: java

我对嵌套循环变量感到困惑。这些循环以某种方式给出了相同的结果,但是我无法将其包裹住。例如,在第二个代码中,它说的是col

 for (int row = 0; row < 4; row++)                                    
 {
    for (int col = 0; col < 3; col++)
    {
       System.out.print(values[row][col] + " ");
    }

    System.out.println();   
}
for (int row = 0; row < values.length; row++)
{
   for (int col = 0; col < values[row].length; col++)
   {
      System.out.print(values[row][col] + " ");
   }

   System.out.println();    
}

3 个答案:

答案 0 :(得分:4)

我不确定您要在这里问什么,但我想您只是想知道这两个代码块之间的区别。

我将通过一个简单的示例向您说明:

import java.util.*;
public class HelloWorld{

     public static void main(String []args){
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int m = sc.nextInt();
        int[][]values = new int[n][m];
        for(int i=0; i<n;i++){
            for(int j=0; j<m; j++){                //read a 5 x 8 array
                values[i][j]= sc.nextInt();
            }
        }
        System.out.print("Input Array :");
        for(int i=0; i<n;i++){
            for(int j=0; j<m; j++){
                System.out.print(values[i][j] +" ");
            }
            System.out.println("");
        }
        System.out.print("First Code :");
        for (int row = 0; row < 4; row++)                                    
        {
             for (int col = 0; col < 3; col++)
             {
                  System.out.print(values[row][col] + " ");
             }
            System.out.println();   
        }
        System.out.print("Second Code :");    
        for (int row = 0; row < values.length; row++)
        {
            for (int col = 0; col < values[row].length; col++)
            {
                 System.out.print(values[row][col] + " ");
            }

            System.out.println();    
         }    
     }
}

输入:

5 8 
3 3 3 3 3 3 3 3 
4 4 4 4 4 4 4 4
5 5 5 5 5 5 5 5 
6 6 6 6 6 6 6 6 
7 7 7 7 7 7 7 7 

程序输出为:

Input Array :3 3 3 3 3 3 3 3 
4 4 4 4 4 4 4 4 
5 5 5 5 5 5 5 5 
6 6 6 6 6 6 6 6 
7 7 7 7 7 7 7 7 
First Code :3 3 3 
4 4 4 
5 5 5 
6 6 6 
Second Code :3 3 3 3 3 3 3 3 
4 4 4 4 4 4 4 4 
5 5 5 5 5 5 5 5 
6 6 6 6 6 6 6 6 
7 7 7 7 7 7 7 7 

因此,如您所见,如果values.length = 4和values [row] .length = 3,则第一个块的工作原理与第二个块完全相同,否则它们将给出不同的结果。遍历数组的好习惯是使用array.length而不是硬编码length的值。

答案 1 :(得分:2)

在冷杉循环中:

System.out.print(values [0] [0] +“”);

System.out.print(values [0] [1] +“”);

System.out.print(values [0] [2] +“”);

System.out.print(values [1] [0] +“”);

System.out.print(values [1] [1] +“”);

System.out.print(values [1] [2] +“”);

.......

,依此类推。...由于行数= 4,因此intern循环将运行4倍。因此,intern循环(col循环)的输出为4 * 3 = 12 System.out.print() 。得到它?行* Col是您要查找的方程式。用它来计算第二个代码。为了提供更多帮助,请显示在值参数中定义的值。

答案 2 :(得分:1)

对于第一部分中的For循环,您尝试遍历4 x 3数组。因此,对于每一行,都会遍历指定的列数。它停在最后一行的最后一列。

对于第二部分中的for循环,我认为当您不知道行和列的值时更合适。

在第二种情况下,第一个完成取决于行的长度,但在第一个情况下是固定的