0

I am new to Java.

My loop array goes out of bounds. I think my code is all fine.

Can someone help me?

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("");
    }
Jeroen Steenbeeke
  • 3,884
  • 5
  • 17
  • 26
Faizzul Hariz
  • 81
  • 1
  • 9

3 Answers3

3

Arrays in java are zero based. So your loop must start at index 0 and the end is lowther than 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("");
    }
Jens
  • 67,715
  • 15
  • 98
  • 113
0

Java array index is 0-based, so it goes from 0 to seats.length-1. Replace <= with < should do

Tony Vu
  • 4,251
  • 3
  • 31
  • 38
0

The arrays starts from key 0 and ended at 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("");
    }
Islam Zedan
  • 656
  • 4
  • 21