0

我正在尝试一些新波士顿的练习视频,但无法正常工作!我对java很陌生,这是我的第一堂课。我有一个任务要做一个二维数组,但我不知道如何让它显示在屏幕上。这种做法来自 Thenewboston 的 Java 教程,视频 #34,它对他有用!

public class inventory {
public static void main (String[] args) {
    int firstarray[][]= {{8,9,10,11},{12,13,14,15}};
    int secondarray[][]={{30,31,32,33},{43},{4,5,6}};

    System.out.println("This is the first array");              
    display(firstarray);
    System.out.println("This is the second array");
    display(secondarray);
    }


public static void display (int x[][])
{
    for(int row=0;row<x.length;row++)
    {
        for(int column=0;column<x.length;column++);
            System.out.print(x[row][column]+"\t");
        }

     { 

    System.out.println();
     }

} }

4

2 回答 2

6

;在 for 循环之后放置了一个,否定了您认为是它的主体的内容。摆脱

for(int column=0;column<x.length;column++); // <--- this ; 

在这种情况下,声明变量并具有作用域的for循环体是 . 之后和 . 之前的所有内容。换句话说,什么都没有。您实际上需要将 替换为.column);;{


正确的缩进对帮助您编写语法正确的代码大有帮助。

于 2013-10-10T19:41:51.903 回答
1

You have semicolon at the end of for cycle and not good formating. There are also two brackets, which are absolutely useless :). The right code can look like this :

public static void display(int x[][]) {
    for (int row = 0; row < x.length; row++) {
        for (int column = 0; column < x.length; column++) {
            System.out.print(x[row][column] + "\t");
        }
        System.out.println();
    }
}

Still the display function is not correct, it fails at the end, because the difference of length of rows and columns.

If you want to make this functional, at the second for cycle, you should consider the length of the actual ROW, not how many rows (which is x.length).

You only need change column < x.length to column < x[row].length

So the working code is this :

public static void display(int x[][]) {
    for (int row = 0; row < x.length; row++) {
        for (int column = 0; column < x[row].length; column++) {
            System.out.print(x[row][column] + "\t");
        }
        System.out.println();
    }
}
于 2013-10-10T19:46:11.643 回答