如何使用`while`循环执行此任务?

时间:2017-12-04 12:29:32

标签: java arrays for-loop while-loop

我不知道如何从for循环转换为while循环我的所有尝试都失败了。我有以下代码:

public static void main(String[] args) {
    int[][] arr = new int[4][];
    arr[0] = new int[4];
    arr[1] = new int[2];
    arr[2] = new int[1];
    arr[3] = new int[3];

int counter = 1;

如何将此for循环转换为while循环?

 //fill arr numbers from 1 to 10
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++) {
                arr[i][j] = counter++;
            }
        }

    for (int i = 0; i < arr.length; i++) {
            System.out.print(" arr [ " + i + " ] = ");
            for (int j = 0; j < arr[i].length; j++) {
                System.out.print(arr[i][j] + " ");
            }
            System.out.println(" ");
        }

    }
}

输出:

arr [ 0 ] = 1 2 3 4  
arr [ 1 ] = 5 6  
arr [ 2 ] = 7 
arr [ 3 ] = 8 9 10

4 个答案:

答案 0 :(得分:2)

for循环基本上是编写while循环的紧凑方式。

for (int i = 0; i < arr.length; i++) { 
  ... 
}

与:

相同
int i=0;
while(i<arr.length){
  ....
  i++;

}

答案 1 :(得分:0)

[
  {
    "_id": "test",
    "a": 1,
    "c": 2
  }
]

这可能会对你有帮助。

答案 2 :(得分:0)

int i = 0;
while ( i < arr.length ) {
int j = 0;
    while ( j < arr[i].length;)
       {
        arr[i][j] = counter++;
       j++;
       }
i++;
}

然后打印值

int i = 0;
while ( i < arr.length ) {
    System.out.print(" arr [ " + i + " ] = ");
    int j = 0;
    while ( j < arr[i].length) {
        System.out.print(arr[i][j] + " ");
     j++;
    }
    System.out.println(" ");
i++;
}

答案 3 :(得分:0)

for循环和while循环的语法不同。相当于for循环:

for(int i = 0; i < arr.length; i++) {
    ...
}

int i = 0;
while(i < arr.length) {
    ...
    i++;
}

以下是您的代码,但有while个循环:

public static void main(String[] args) {
    int[][] arr = new int[4][];
    arr[0] = new int[4];
    arr[1] = new int[2];
    arr[2] = new int[1];
    arr[3] = new int[3];

    int counter = 1;
    int i = 0, j = 0; // Initialize vars for while loops

    //fill arr numbers from 1 to 10     
    while(i<arr.length){
        while(j<arr[i].length){
            arr[i][j] = counter++;
            j++; // Increment as in for loops
        }
        i++; // Increment as in for loops
        j = 0; // Restart j to the next outer loop step
    } 

    i = 0; // Reset i for outer loop
    // No need to j=0 since when the above loop ends, j will reset to 0

    while(i<arr.length){
        System.out.print(" arr [ " + i + " ] = ");
        while(j<arr[i].length){
            System.out.print(arr[i][j] + " ");
            j++; // Increment as in for loops
        }
        i++; // Increment as in for loops
        j = 0; // Same objective as in the loop above
        System.out.println(" ");
    }
}

评论中的解释,希望它有所帮助!