2013-02-16 51 views
0

我正在個人項目上工作,但我有一個問題,我似乎無法弄清楚。掃描儀故障。沒有腳本錯誤,但控制檯給出錯誤

public void setvars() { 
    File file = new File("config.txt"); 

    try { 
     Scanner sc = new Scanner(file); 

     while(sc.hasNextLine()) { 
      //int OESID = sc.nextInt(); this variable isnt used yet. 
      String refresh = sc.next(); 
      sc.close(); 

      textFieldtest.setText(refresh); 
     } 
    } 
    catch (Exception e) 
    { 
     e.printStackTrace(); 
    } 
} 

在它告訴我的錯誤是while(sc.hasNextLine()) {控制檯我不能弄明白。任何指針/建議將不勝感激!

+0

有什麼錯誤?什麼是掃描儀對象? – 2013-02-16 15:55:48

回答

0

問題是您在使用掃描儀時正在關閉掃描儀。

修改代碼以關閉掃描儀一旦你用它做:

while(sc.hasNextLine()) { 
     //int OESID = sc.nextInt(); this variable isnt used yet. 
     String refresh = sc.next(); 

     textFieldtest.setText(refresh); 
    } 
    sc.close(); 

這也許應該是,每當你處理任何資源使用通用的模式 - 確保您關閉它只有一次,你」確信你不再需要它了。

你可以讓你的生活更容易,如果你使用的是Java 7通過使用新的嘗試,與資源的功能,它會自動關閉資源:

try(Scanner sc = new Scanner("/Users/sean/IdeaProjects/TestHarness/src/TestHarness.java")) { 
     while(sc.hasNextLine()) { 
      // do your processing here 
     } 
    } // resource will be closed when this block is finished 
+0

啊!完善!非常感謝! – user2078674 2013-02-16 17:08:19