[英]Using BufferedReader to grab values from a 2D array throwing NullPointerException
I need to grab integer values from a.txt file using the BufferedReader, and then save them to a 2D int array.我需要使用 BufferedReader 从 a.txt 文件中获取 integer 值,然后将它们保存到 2D int 数组中。 For some reason, when I get to the
.trim()
line, it throws a NullPointerException.出于某种原因,当我到达
.trim()
行时,它会抛出 NullPointerException。 Each of the numbers in my array are separated by a space in the file:我的数组中的每个数字都由文件中的空格分隔:
90 47 110 95 95
101 87
54 0 38 12
Here is the broken code I have for reading then saving the integers:这是我读取然后保存整数的损坏代码:
int2DArr = new int[int2Drows][int2Dcolumns];
String s;
while((s = br.readLine()) != null){
for(int i = 0; i<int2DArr.length; i++){
String[] currLine = br.readLine().trim().split(" "); //throwing error here
for(int j = 0; j<currLine.length; j++){
int2DArr[i][j] = Integer.parseInt(currLine[j]);
}
}
}
Any help would be greatly appreciated!任何帮助将不胜感激!
I think the problem is that there is an extra readLine()
.我认为问题在于有一个额外的
readLine()
。 You are already reading the next line in the while
loop.您已经在阅读
while
循环中的下一行。 So inside the loop you should use the s
instead of reading the next line.所以在循环内你应该使用
s
而不是阅读下一行。 With your current code, you are reading 2 lines per iteration in the while
loop but you intended to read 1 line per iteration.使用您当前的代码,您在
while
循环中每次迭代读取 2 行,但您打算每次迭代读取 1 行。
Note the change just before the trim
call.请注意在
trim
调用之前的更改。
int2DArr = new int[int2Drows][int2Dcolumns];
String s;
while((s = br.readLine()) != null){
for(int i = 0; i<int2DArr.length; i++){
String[] currLine = s.trim().split(" ");
for(int j = 0; j<currLine.length; j++){
int2DArr[i][j] = Integer.parseInt(currLine[j]);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.