javaarraysmatrix

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.


Solution

  • 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.