2017-02-20 22 views
0

我正在執行此程序,並且在輸出結束時,我始終收到「null」錯誤,正如您在代碼中看到的一樣。它確實讀取文件,但最後,它增加了很多null。任何指導將不勝感激! 這是我到目前爲止所嘗試的。讀取文件後輸出中的空錯誤

public static void main(String[] args) throws Exception 
{ 
    Stack nifo=new Stack(); 
    FileReader file = new FileReader("infix.dat"); 
    try (BufferedReader br = new BufferedReader(file)) { 
     String [] words = new String[50]; 
     String text=""; 
     int ctrl = 0; 
     String Line =br.readLine(); 
     while (Line!= null) 
      { 
      words[ctrl]= Line; 
      Line = br.readLine(); 
      ctrl = ctrl + 1; 
      }//end of while loop 


      for (int i = 0; i < words.length; i++) 
      { 
      System.out.println(words[i]); 
      } 
      file.close(); 
     } catch (IOException e) { 
     e.printStackTrace(); 
    }//end of catch 

}//end of main class 

我的輸出結果如下。正如你所看到的,在我讀完我的文件後,null會被打印在最後。

5 * 6 + 4 
3 - 2 + 
(3 * 4 - (2 + 5)) * 4/2 
10 + 6 * 11 -(3 * 2 + 14)/2 
    2 * (12 + (3 + 5) * 2 
    null 
    null 
    null 
    null 
    more nulls after that. 

謝謝!

+1

這不是錯誤,那是數組中的所有空白空間。 – azurefrog

回答

0

因爲你不知道數組的大小,如果你要堅持使用數組那麼下面可能會解決你的問題

 for (int i = 0; i < words.length && words[i] != null; i++) 
     { 
      System.out.println(words[i]); 
     } 
     file.close(); 

只要確保您的循環不處理單詞數組中任何索引的空值。因爲當您聲明修復大小的數組時,從未在數組中填充過的索引初始化爲空

+0

感謝您的輸入和快速回答。 – mike

+0

希望這對你有所幫助,因爲我沒有興趣用其他數據結構替換你的數組。但如果你正在尋找多樣性,其他答案仍然值得嘗試:) – ShayHaned

1

您聲明固定大小的數組:

String[] words = new String[50]; 

然後您存儲在它的一些值,然後打印每個元素:

for (int i = 0; i < words.length; i++) { 
    System.out.println(words[i]); 
} 

所有你不使用的元素爲空。所以如果你的文件有6行,它會打印出6行,然後是44個null,因爲你沒有在其他44個插槽中放置任何東西。我建議你使用不同的數據結構,如列表。這將允許您僅存儲您需要的值的數量。

試試這個:

public static void main(String[] args) throws Exception 
{ 
    Stack nifo=new Stack(); 
    FileReader file = new FileReader("infix.dat"); 
    try (BufferedReader br = new BufferedReader(file)) { 
     List<String> words = new LinkedList<>(); //replaced your array with a list 
     String text=""; 
     String Line =br.readLine(); 
     while (Line!= null) 
      { 
      words.add(Line); 
      Line = br.readLine(); 
      }//end of while loop 

      for (String word : words) 
      { 
      System.out.println(word); 
      } 
      file.close(); 
     } catch (IOException e) { 
     e.printStackTrace(); 
    }//end of catch 

}//end of main class 
+0

非常感謝你和謝謝你的提示鏈接列表! – mike

+0

@mike樂意幫忙!請記住upvote並接受答案,如果這解決了您的問題=] – nhouser9