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