Using a for loop to Print and Two-Dimensional Array in Java
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]);
}
}
You may want something like that :
Preferences [0][0]="Tom";
Preferences [0][1]="Coke";
Preferences [1][0]="John";
Preferences [1][1]="Pepsi";
You'll know that Preferences[0] is about Tom
You'll know that Preferences[1] is about John
And once you have it, the columns will be [0]=>"name" [1] =>"drink"
[0][1] will give you Tom[0] s drink[1] [Coke] for example.
[0][0] will give you Tom[0] s name[0] [Tom] for example.
[1][1] will give you John[1] s drink[1] [Pepsi] for example.
[1][0] will give you John[1] s name[0] [John] for example.
for (int i=0; i<2; i++){
//size for inner loop was 3 but should be 2
for (int j =0; j<2; j++){
System.out.print(Preferences[i][j]);}
}
}
For 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]);}
}
}