在Java中使用for循环打印和二维数组

Dan*_*yer 7 java arrays matrix

我正在尝试完成一项任务(所以在一般方向上的要点会有很大帮助)我必须(按顺序):

  1. 声明一个二维字符串数组,
  2. 将值分配给两个人和他们最喜欢的饮料的数组
  3. 使用for循环输出

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]);
            }
        }
    }   
}
Run Code Online (Sandbox Code Playgroud)

我收到此错误消息

Tom,CokenullException在线程"main"java.lang.ArrayIndexOutOfBoundsException:2在doublearray.main(doublearray.java:15)

现在,我明白",汤姆,可乐"只被分配给ONE [0],这就是出现null的原因,但我不知道如何解决这个问题或者让它成功打印.

任何帮助都会非常感激,我已经坚持了大约一个小时.谢谢你们.

Ósc*_*pez 10

试试这个,这是遍历任意大小的二维数组的正确方法:

for (int i = 0; i < Preferences.length; i++) {
    for (int j = 0; j < Preferences[i].length; j++) {
        System.out.print(Preferences[i][j]);
    }
}
Run Code Online (Sandbox Code Playgroud)


Mic*_*gue 4

你可能想要这样的东西:

Preferences [0][0]="Tom";
Preferences [0][1]="Coke";
Preferences [1][0]="John";
Preferences [1][1]="Pepsi";
Run Code Online (Sandbox Code Playgroud)

您会知道 Preferences[0] 是关于 Tom
您会知道 Preferences[1] 是关于 John

一旦你拥有它,列将是 [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.
Run Code Online (Sandbox Code Playgroud)