2012-07-16 125 views
1

幫助再次傢伙,爲什麼我總是會在使用掃描儀時出現這種錯誤,即使我確定該文件存在。沒有行發現異常

java.util.NoSuchElementException:沒有找到行

我試圖用for循環計數的a出現次數的數量。該文本文件包含句子的行。同時,我想打印確切的句子格式。

Scanner scanLine = new Scanner(new FileReader("C:/input.txt")); 
while (scanLine.nextLine() != null) { 
    String textInput = scanLine.nextLine(); 
    char[] stringArray = textInput.toCharArray(); 

    for (char c : stringArray) { 
     switch (c) { 
      case 'a': 
      default: 
       break; 
     } 
    } 
} 
+3

switch(x)對不對? – 2012-07-16 07:27:40

回答

4
while(scanLine.nextLine() != null) { 
    String textInput = scanLine.nextLine(); 
} 

我想說的問題是在這裏:

在你while條件,您掃描的最後一行,來到EOF。之後,你進入循環體並嘗試獲取下一行,但是你已經讀完了文件。將環路條件更改爲scanLine.hasNextLine()或嘗試另一種讀取文件的方法。

閱讀txt文件的另一種方式可以是這樣的:

BufferedReader reader = new BufferedReader(new InputStreamReader(new BufferedInputStream(new FileInputStream(new File("text.txt"))))); 

String line = null; 

while ((line = reader.readLine()) != null) { 
    // do something with your read line 
} 
reader.close(); 

或本:

byte[] bytes = Files.readAllBytes(Paths.get("text.txt")); 
String text = new String(bytes, StandardCharsets.UTF_8); 
+0

非常感謝您 – 2012-07-16 07:28:59

+0

不客氣:D – Lopina 2012-07-16 07:29:17

+2

對於第一部分的答案,對於第二部分,您已經使用了太多不必要的包裝。相反,使用這個'新的BufferedReader(新的FileReader(新的文件(「text.txt」)));' – 2012-07-16 07:30:08

2

您應該使用:scanner.hasNextLine()而不是scanner.nextLine()在同時條件

掃描儀實現了迭代器接口,該接口使用此模式工作:

  • 看看是否有下一個項目(hasNext())
  • 檢索下一個項目(下一個())
1

要計算的出現次數「一」或與此有關的任何字符串一個字符串,你可以使用StringUtils的從apache-commons-lang像:

System.out.println(StringUtils.countMatches(textInput,"a")); 

我認爲這將是比字符串轉換爲字符數組,然後循環整個數組找到的「一」出現的次數更高效。此外,StringUtils方法是無效的安全