2017-03-10 66 views
0

我正在嘗試讀取文件,並將文件中的每一行都設置爲參數,並將其設置爲我製作的對象OS_Process,然後將這些進程放置在鏈接列表隊列中。但是,我一直得到一個nullpointerexception。數據文件如下所示。每一個新的過程數據都在一條新的線上。如何解決我的代碼中的空指針異常?

3 //counter 
1 3 6 //process 1 data 
3 2 6 //process 2 data 
4 3 7 //process 3 data 

這是我的代碼

import java.io.*; 
    import java.util.*; 

    public class OS_Scheduler 
    { 
    public static void main(String[] args) 
    { 
     Queue<OS_Process> jobs = new LinkedList<OS_Process>(); 

     try 
     { 
      System.out.print("Enter the file name: "); 
      Scanner file = new Scanner(System.in); 
      File filename = new File(file.nextLine()); 

      OS_Process proc = null; 
      String s = null; 
      int a = 0, p = 0, b = 0; 
      BufferedReader input = new BufferedReader(new FileReader(filename)); 
      StringTokenizer st = new StringTokenizer(s); 
      int count = Integer.parseInt(st.nextToken()); 
      while ((s = input.readLine()) != null) 
      { 
       st = new StringTokenizer(s); 
       a = Integer.parseInt(st.nextToken()); 
       p = Integer.parseInt(st.nextToken()); 
       b = Integer.parseInt(st.nextToken()); 
       proc = new OS_Process(a, p, b, 0); 
       jobs.add(proc); 
      } 
      input.close(); 
     } 
     catch (Exception ex) 
     { 
      ex.printStackTrace(); 
     } 

    } 
} 

回答

2

你有一個NullpointerException因爲您已設置String s = null;然後調用StringTokenizer stz = new StringTokenizer(s);等於StringTokenizer stz = new StringTokenizer(null);,這得到空指針。

你不需要知道count線路,因爲如果到達文件 的末尾,以便更新您的代碼如下的while -loop遍歷文件中的所有線路將停止:

String s = input.readLine();//read first line to get rid of it 
if(s == null){ 
    //File is empty -> abort 
    System.out.println("The file is empty"); 
    System.exit(0); 
} 
int a = 0, p = 0, b = 0; 
StringTokenizer st; 
while ((s = input.readLine()) != null) 
{...} 

,或者如果你想使用count,你可以做這樣的:

String s = input.readLine(); 
checkReadLineNotNull(s); 
int a = 0, p = 0, b = 0; 
StringTokenizer st = new StringTokenizer(s); 
int count = Integer.parseInt(st.nextToken()); 

for (int i = 0; i < count; i++) { 
    s = input.readLine(); 
    checkReadLineNotNull(s); 
    st = new StringTokenizer(s); 
    //... 
} 

//Checks if s != null otherwise kills the programm 
private static void checkReadLineNotNull(String s) { 
    if(s == null){ 
     //File is empty abort 
     System.out.println("The file is empty"); 
     System.exit(0); 
    } 
} 
+0

我不完全知道如何解決它。無論我初始化什麼,因爲我仍然有錯誤。 – TylerGBrooke

+0

究竟是什麼錯誤?你有'File filename'嗎?請檢查通過'filename.exists()' –

+0

是的,我仍然得到NullpointerException。我將s改爲「」而不是null,但現在我得到一個nosuchelementException。 – TylerGBrooke