我的问题是尝试读取包含不规则数组的文件。我想我差不多了,但我一直得到一个空指针异常错误。欢迎任何帮助或建议。这是我的代码。
import java.io.*;
import java.util.Scanner;
import java.util.*;
public class Calories2{
public static void fileReaderMethod(String fileName) throws FileNotFoundException, IOException {// This method reads the file and inputs the measurements
Scanner input ;
try{ // into an array of type int.
input = new Scanner (new File(fileName));
}
catch (FileNotFoundException e){
System.out.println("File Does Not Exist");
System.out.println("Choose another file");
Scanner in = new Scanner(System.in);
fileName = in.next();
input = new Scanner (new File(fileName));
}
FileReader fr = new FileReader(fileName);
BufferedReader textReader = new BufferedReader(fr);
int row=0;
String currentRow;
while((currentRow = textReader.readLine())!= null){
rows++;
}
fr = new FileReader(fileName);
textReader = new BufferedReader(fr);
String [] columns = textReader.readLine().split(" ");
int [][] caloriesOfTheWeekArray = new int [7][];
fr = new FileReader(fileName);
textReader = new BufferedReader(fr);
for(int i = 0; i < caloriesOfTheWeekArray.length; i++){
String columnArray [] = textReader.readLine().split(" ");
for (int j = 0; j < columns.length; j++){
caloriesOfTheWeekArray[i][j] = Integer.parseInt(columnArray[j]);
}
}
}
public static void main (String [] args)throws FileNotFoundException, IOException {
fileReaderMethod("Calories.txt");
}
}
这是我得到的错误。
Exception in thread "main" java.lang.NullPointerException
at Calories2.fileReaderMethod(Calories2.java:36)
at Calories2.main(Calories2.java:41)
第36行
caloriesOfTheWeekArray[i][j] = Integer.parseInt(columnArray[j]);
和41是我调用读取文件的方法
文件我正在尝试阅读
200 10000
450 845 1200 800
800
400 1500 1800 200
500 1000
700 1400 170
675 400 100 400 300
答案 0 :(得分:0)
问题在于您对caloriesOfTheWeekArray
,
int [][] caloriesOfTheWeekArray = new int [7][];
这将初始化7
行但无法初始化您的列,因为您尚未指定它们。如果没有初始化您的列,您将尝试访问第36行中的列
caloriesOfTheWeekArray[i][j] = Integer.parseInt(columnArray[j]);
这导致你的NPE。
因此请将长度为columnArray.length
的列初始化。
for(int i = 0; i < caloriesOfTheWeekArray.length; i++){
String columnArray [] = textReader.readLine().split(" ");
caloriesOfTheWeekArray[i] = new int[columnArray.length];
for (int j = 0; j < columnArray.length; j++){
caloriesOfTheWeekArray[i][j] = Integer.parseInt(columnArray[j]);
}
}
此外,您使用column.length
代替columnArray.length
,而{i}也负责NPE。