这是我的第一个问题。我正在尝试编写一个程序,该程序读取与从键盘输入一样多的数组。输入列数后出现错误: Exception in thread "main"java.lang.ArrayIndexOutOfBoundsException: 0
提前致谢。
package Final;
import java.util.*;
public class Final {
int a,b,x,l;
double mat[][][];
Final()
{
a=0;
b=0;
c=0;
d=0;
x=0;
l=0;
}
public void read() {
Scanner citast = new Scanner(System.in);
System.out.println("How many arrays do you want to enter?");
x=citast.nextInt();
for (this.l=0; this.l<x; this.l++)
{
System.out.println("Matrix "+this.l);
System.out.println("Number of lines: ");
this.a = citast.nextInt();
System.out.println("Number of columns: ");
this.b = citast.nextInt();
this.mat= new double [this.l][a][b];
for (int i=0; i<this.a; i++)
{
for (int j=0; j<this.b; j++)
{
System.out.print("Matrice " + l + " ["+ i +"]["+ j +"]= ");
this.mat[l][i][j]=citast.nextInt();
}
System.out.println();
}
}
}
public static void main(String[] args) {
Final a = new Final();
Scanner citast = new Scanner(System.in);
a.read();
System.out.println();
}
}
最佳答案
this.mat= new double [this.l][a][b];
应该是:
this.mat= new double [x][a][b];
但是你的代码是错误的,你应该在第一个 for 循环之前设置数组的维度:
public void read() {
Scanner citast = new Scanner(System.in);
System.out.println("How many arrays do you want to enter?");
x=citast.nextInt();
this.mat = new double[x][][]; //<-- added this line
for (this.l=0; this.l<x; this.l++)
{
System.out.println("Matrix "+this.l);
System.out.println("Number of lines: ");
this.a = citast.nextInt();
System.out.println("Number of columns: ");
this.b = citast.nextInt();
this.mat[l] = new double [a][b]; //<-- modified this line
for (int i=0; i<this.a; i++)
for (int j=0; j<this.b; j++)
{
System.out.print("Matrice " + l + " ["+ i +"]["+ j +"]= ");
this.mat[l][i][j]=citast.nextInt();
}
System.out.println();
}
System.out.println(Arrays.deepToString(mat));
}
包含 2 个方阵的数组的输出(一个用 4 填充,一个用 5 填充):
[[[4.0, 4.0], [4.0, 4.0]], [[5.0, 5.0], [5.0, 5.0]]]
关于java - 3维数组索引越界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20176028/