0
免责声明:这是作业,所以我不想找到确切的答案,因为我想自己做这件事。 我必须从充满双打的文本文件中读取一个矩阵,并将其放入二维数组中。 我目前正在努力寻找我的问题在我的代码中的确切位置,因为我知道如何使用内置的Java扫描器来创建正常的数组。我的代码总是给我一个NullPointerException错误,这意味着我的矩阵二维数组是空的。读一个充满双打的文本文件到一个二维数组中
public Matrix(String fileName){
//reads first double and puts it into the [1][1] category
//then moves on to the [1][2] and so on
//once it gets to the end, it switches to [2][1]
Scanner input = new Scanner(fileName);
int rows = 0;
int columns = 0;
while(input.hasNextLine()){
++rows;
Scanner colReader = new Scanner(input.nextLine());
while(colReader.hasNextDouble()){
++columns;
}
}
double[][]matrix = new double[rows][columns];
input.close();
input = new Scanner(fileName);
for(int i = 0; i < rows; ++i){
for(int j = 0; j < columns; ++j){
if(input.hasNextDouble()){
matrix[i][j] = input.nextDouble();
}
}
}
}
我的文本文件:
1.25 0.5 0.5 1.25
0.5 1.25 0.5 1.5
1.25 1.5 0.25 1.25
NullPointerException发生在哪里?查看堆栈跟踪并查看是否可以确定发生异常的行。 – Defenestrator
@Ravi这个问题非常笼统,过于宽泛。我不打算把这个问题作为这个问题的重复来解决。 – Defenestrator
@Defenestrator错误发生在我的* toString()*函数中,这是我的嵌套for循环的第一个看到2d数组的长度。 – Michael