JAVA初学者数组2d循环出界

时间:2017-03-15 10:05:32

标签: java arrays

我是java新手。

我的循环数组越界。我认为我的代码很好。

有人可以帮助我。 Sry for bad english

String[][] seats = new String[5][3];

for(int r = 1; r <= seats.length; r++){
        System.out.printf(r+ "." );

        for (int c = 1; c <= seats[r].length; c++){
            System.out.print("  0");
        }

        System.out.println("");
    }

3 个答案:

答案 0 :(得分:2)

Java中的数组是基于零的。所以你的循环必须从索引0开始,然后结束低于Array.length for(int r = 0; r < seats.length; r++){

String[][] seats = new String[5][3];

for(int r = 0; r < seats.length; r++){
        System.out.printf(r+ "." );

        for (int c = 0; c < seats[r].length; c++){
            System.out.print("  0");
        }

        System.out.println("");
    }

答案 1 :(得分:0)

Java数组索引从0开始,因此它从0到seat.length-1。替换&lt; = with&lt;应该做

答案 2 :(得分:0)

数组从键0开始,以array.length-1

结束
String[][] seats = new String[5][3];

for(int r = 0; r < seats.length; r++){
        System.out.printf(r+ "." );

        for (int c = 1; c <= seats[r].length; c++){
            System.out.print("  0");
        }

        System.out.println("");
    }