免责声明:这是家庭作业,所以我不是在寻找一个确切的答案,因为我想自己这样做。 我必须从填充了双精度的文本文件中读取矩阵并放入2D数组中。 我目前正努力找到我的问题究竟在哪里,因为我知道如何将内置的Java Scanner用于普通数组。我下面的代码总是给我一个NullPointerException错误,这意味着我的 矩阵 2D数组是空的。
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
答案 0 :(得分:1)
您的代码有一些错误 - 因为它是作业,我会尽可能地坚持您的原始设计:
public Matrix(String fileName){
//First issue - you are opening a scanner to a file, and not its name.
Scanner input = new Scanner(new File(fileName));
int rows = 0;
int columns = 0;
while(input.hasNextLine()){
++rows;
columns = 0; //Otherwise the columns will be a product of rows*columns
Scanner colReader = new Scanner(input.nextLine());
while(colReader.hasNextDouble()){
//You must "read" the doubles to move on in the scanner.
colReader.nextDouble();
++columns;
}
//Close the resource you opened!
colReader.close();
}
double[][]matrix = new double[rows][columns];
input.close();
//Again, scanner of a file, not the filename. If you prefer, it's
//even better to declare the file once in the beginning.
input = new Scanner(new File(fileName));
for(int i = 0; i < rows; ++i){
for(int j = 0; j < columns; ++j){
if(input.hasNextDouble()){
matrix[i][j] = input.nextDouble();
}
}
}
}
请注意评论 - 总体而言,您距离功能代码不远,但错误很重要。