gpt4 book ai didi

java - 将充满 double 的文本文件读取到二维数组中

转载 作者:行者123 更新时间:2023-12-02 12:12:47 25 4
gpt4 key购买 nike

免责声明:这是家庭作业,所以我不想寻找确切的答案,因为我想自己做。我必须从充满 double 的文本文件中读取矩阵并将其放入二维数组中。我目前正在努力寻找代码中的问题所在,因为我知道如何使用内置的 Java Scanner 来处理普通数组。我下面的代码总是给我一个 NullPointerException 错误,这意味着我的 matrix 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

最佳答案

您的代码有几个错误 - 由于这是家庭作业,我会尽力坚持您的原始设计:

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

请注意注释 - 总的来说,您离功能代码不远了,但理解错误很重要。

关于java - 将充满 double 的文本文件读取到二维数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46411419/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com