2013-09-26 219 views
1

我正在嘗試使用掃描儀讀取使用JFileChooser拉出的文本文件。 wordCount工作正常,所以我知道它正在閱讀。但是,我無法得到它來搜索用戶輸入單詞的實例。使掃描儀讀取文本文件

public static void main(String[] args) throws FileNotFoundException { 
    String input = JOptionPane.showInputDialog("Enter a word"); 
    JFileChooser fileChooser = new JFileChooser(); 
    fileChooser.showOpenDialog(null); 
    File fileSelection = fileChooser.getSelectedFile(); 
    int wordCount = 0; 
    int inputCount = 0; 
    Scanner s = new Scanner (fileSelection); 
    while (s.hasNext()) { 
     String word = s.next(); 
     if (word.equals(input)) { 
      inputCount++; 
    } 
    wordCount++; 
} 
+2

給我們一個你的文件內容和輸入的例子。 –

+0

你是如何顯示inputCount的?你在一些GUI上更新它嗎? –

+0

將它打印到控制檯。我想這可能是因爲這個詞後面跟着一段時間。 – user2792660

回答

0

您需要查找

; 。 ! ?等等。

爲每個單詞。 next()方法捕獲整個字符串,直到遇到empty space

它會考慮「嗨,你好嗎?」如下「嗨」,「如何」,「是」,「你?」。

您可以使用方法indexOf(String)來查找這些字符。你也可以使用replaceAll(String regex,String replacement)替換字符。你可以個性化刪除每個字符,或者你可以使用Regex,但這些通常會更復雜。

//this will remove a certain character with a blank space 
word = word.replaceAll(".",""); 
word = word.replaceAll(",",""); 
word = word.replaceAll("!",""); 
//etc. 

瞭解更多關於此方法:

http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#replaceAll%28java.lang.String,%20java.lang.String%29

這裏有一個正則表達式例子:

//NOTE: This example will not work for you. It's just a simple example for seeing a Regex. 
//Removes whitespace between a word character and . or , 
String pattern = "(\\w)(\\s+)([\\.,])"; 
word = word.replaceAll(pattern, "$1$3"); 

來源:

http://www.vogella.com/articles/JavaRegularExpressions/article.html

這裏是一個很好的正則表達式的例子,可以幫助你:

Regex for special characters in java

Parse and remove special characters in java regex

Remove all non-"word characters" from a String in Java, leaving accented characters?

+0

有沒有辦法讓掃描器忽略標點符號? – user2792660

+0

@ user2792660更新的答案 –

+0

我認爲我提供的方法更全面,因爲所有東西都被'。*'接受。 replaceAll方法會遇到未指定特殊符號的問題。在這個特殊情況下''''或者一些外國跡象。 – mike

0

如果用戶inputed文本在不同的情況下,那麼你應該嘗試除了blackpanthers使用equalsIgnoreCase()

+0

我想這可能是因爲這個詞後面跟着一個句點。有沒有辦法消除這種情況? – user2792660

0

回答,你也應該用TRIM()佔whitespaces.as 「ABC」不等於到「abc」

0

你應該看看matches()

equals不會幫你,因爲next()不按單詞返回該文件的話, 而是空白(逗號,分號等)通過令牌分開令牌(如其他人所說)。

這裏的Java文檔
String#matches(java.lang.String)

...和一個小例子。

input = ".*" + input + ".*"; 
... 
boolean foundWord = word.matches(input) 

.是正則表達式通配符,代表任何符號。 .*代表0個或更多未定義的符號。所以你得到一個匹配,如果輸入是在word的某處。