I am trying to complete an assignment (so point in the general direction would help greatly) within which I have to (in order):
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.
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]);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With