2013-11-03 38 views
0

txt文件,我有一個包含這一個txt文件:的邏輯錯誤,而試圖掃描特定的詞

Mary had a little lamb little lamb 
little lamb. Mary had a little lamb. 
That's all? Did the lamb follow Mary 
wherever Mary went? 

我嘗試寫一些代碼,掃描單詞「瑪麗」 txt文件,統計它出現的次數,然後打印該數字。

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

class Test { 
    public static void main(String[] args) { 
     int count = 0; 

     Scanner reader = new Scanner("test.txt"); 

     while (reader.hasNextLine()) { 
      String nextToken = reader.next(); 
      if (nextToken.equals("Mary")) 
       count++; 
     } 

     System.out.println("The word 'Mary' was found on " + count + " lines."); 
    } 


} 

雖然代碼編譯,我不斷收到不正確的輸入,與系統打印"The word 'Mary' was found on 0 lines."

任何想法是怎麼回事?

+3

'contains()'而不是'equals()' –

回答

4

你實際上並不是從文件中讀取數據。

您需要聲明掃描儀爲new Scanner(new File("test.txt"));否則,掃描儀會逐字掃描Mary的字符串「test.txt」。

Scanner文檔的不同構造

+0

感謝您的快速響應!我試着做出修改,但系統拋出「未報告的異常FileNotFoundException;必須被捕獲或聲明拋出」錯誤:/ – user2893128

+0

@ user2893128您確定該文件位於正確的位置? –

+0

@ user2893128您可以給出文本文件的完整路徑(即「C:\\ Users \\ user \\ Desktop \\ test.txt」),或者您可以將文本文件移動到與Test.class相同的位置文件 – vandale

0

vandale是正確的在new Scanner("test.txt")應該new Scanner(new File("test.txt"))

但是,如果您想查找單詞「Mary」的行數,則需要稍微更改一下代碼。看看有評論的行:

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

class Test { 
    public static void main(String[] blargs) { 
     int count = 0; 

     Scanner reader = new Scanner(new File("test.txt")); 

     while (reader.hasNextLine()) { 
      String nextToken = reader.nextLine(); // nextLine() instead of next(). 
      if (nextToken.contains("Mary")) // contains() instead of equals() 
       count++; 
     } 
     System.out.println("The word 'Mary' was found on " + count + " lines."); 
    } 
}