1

我需要一些关于这个数组的帮助来显示输出,但它似乎不像我期望的那样工作。

public static void main(String[] args){


            String[][] record = {
                {"abc","123","cbv"},
                {"efg","456","cbb"},
                {"hij","321","ggb"},
                {"xyz","A4","ghy"}};


            for (int i=0;i<4;i++){
                for (int j=0;j<3;j++)
                System.out.println(record[i][j]);

输出显示:

abc
123
cbv
efg
456
cbb
hij
321
ggb
xyz
A4
ghy

我需要输出显示为:

abc 123 cbv
efg 456 ccb
hij 321 ggb
xyz A4 ghy
4

3 回答 3

4

You should do:

for (int i=0;i<4;i++) {
    for (int j=0;j<3;j++) {
        System.out.print(record[i][j] + " ");  // print instead of println
    }
    System.out.println();                      // println (new row)
}

(The inner loop which prints elements in one row should not print line-breaks.)

Or, even better, use System.out.printf to make sure all elements are equally wide (this example also uses for each loops):

for (String[] row : record) {
    for (String element : row)
        System.out.printf("%5s", element);
    System.out.println();
}

Output:

  abc  123  cbv
  efg  456  cbb
  hij  321  ggb
  xyz   A4  ghy
于 2012-04-25T10:31:41.143 回答
0
for (int i=0;i<4;i++){
    for (int j=0;j<3;j++) {
        System.out.print(record[i][j]);
    }
    System.out.println();
}

should do it.

于 2012-04-25T10:32:28.727 回答
0
for (int i=0;i<4;i++) {
for (int j=0;j<3;j++) {
    System.out.print(record[i][j] + " ");  // print instead of println

}
System.out.println();                      // println (new row)
}
于 2012-04-25T10:36:24.560 回答