ArrayIndexOutOfBounds异常,使用scanner来读取数组元素

时间:2013-12-07 18:27:01

标签: java

我想通过从用户那里获取输入以矩阵形式打印数组。我来到这段代码,但是这段代码抛出了ArrayIndexOutOfBound的例外。我努力了,但我无法得出任何结论,所以请帮助我。

以下是代码:

System.out.println("Enter the row i.e no. of array in x");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();

System.out.println("Enter the size of array");

int y[] = new int[n];
for (int i = 1; i < y.length; i++) {
    y[i] = sc.nextInt();
}
int z[][] = new int[n][];
for (int i = 1; i < y.length; i++) {
    z[i] = new int[y[i]];
}
System.out.println("Enter the elements of array");
for (int i = 1; i < z.length; i++) {
    for (int j = 1; j < z[i].length; j++) {
        z[i][j] = sc.nextInt();
    }
}
System.out.println("Matrix is");
for (int i = 1; i < z.length; i++) {
    for (int j = 1; j < z[i].length; j++) {
        System.out.print(z[i][j]);
        System.out.print("\t");
    }
    System.out.println();
}

1 个答案:

答案 0 :(得分:1)

这是无效的。

int y[] = new int[n];
for (int i = 1; i < y.length; i++) {
    y[i] = sc.nextInt();
}

数组是0索引的:

int y[] = new int[n];
for (int i = 0; i < y.length; i++) {
    y[i] = sc.nextInt();
}

您需要更改所有迭代。