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



我想通过接受用户的输入来打印矩阵形式的数组。我得到了这个代码,但这个代码抛出了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();
}

这是无效的。

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();
}

您需要更改所有迭代。

最新更新