2017-02-05 54 views
0

我的问题是尝试读取包含不齐整数组的文件。我想我几乎在那里,但我不断收到空指针异常错误。欢迎任何帮助或建议。这是我的代码。将文件读入不规则数组

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 
+2

发布您的错误跟踪以及。 –

+0

你的意思是我得到的错误? –

+0

@Micheal yupp,你得到的错误。 –

回答

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哪些IA还负责NPE。

+0

让我知道这是否帮助你。 –

+0

是的,非常感谢。它读取光线的方式在某些部分和其他部分都是正确的,因此无法获得文件中的数字。但我想我可以自己找到问题。谢谢。 –