Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a for loop to Print and Two-Dimensional Array in Java

I am trying to complete an assignment (so point in the general direction would help greatly) within which I have to (in order):

  1. Declare a 2d String Array,
  2. Assign Values to the array of two people and their favourite drink
  3. Output using a for loop

public class doublearray {
    public static void main(String[] args){
        String Preferences [] [] = new String [2][2];
        Preferences [0][0]= "Tom, Coke";
        Preferences [1][1]= "John, Pepsi";

        for (int i=0; i<2; i++){
            for (int j =0; j<3; j++){
                System.out.print(Preferences[i][j]);
            }
        }
    }   
}

I receive this error message

Tom, CokenullException in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2 at doublearray.main(doublearray.java:15)

Now, I understand that ",Tom,Coke" have been assigned only to ONE [0] which is why null appears, but I've no idea how to remedy that or make it print successfully.

Any help would be most appreciated, I've been stuck on this for about an hour. Thank ya'll.

like image 876
Dan Wyer Avatar asked Aug 01 '13 14:08

Dan Wyer


1 Answers

Try this, it's the correct way to traverse a two-dimensional array of arbitrary size:

for (int i = 0; i < Preferences.length; i++) {
    for (int j = 0; j < Preferences[i].length; j++) {
        System.out.print(Preferences[i][j]);
    }
}
like image 106
Óscar López Avatar answered Oct 08 '22 11:10

Óscar López