2013-04-07 127 views
0

我正在編寫一個方法來搜索列表形式的單詞文本文件,對於由用戶輸入但由程序輸入的單詞將返回肯定的結果,如果一個字母在所有被發現,例如,如果我搜索「F」,它將返回有在字典中的單詞「F」時,有沒有正在搜索一個文本文件

public static void Option3Method(String dictionary) throws IOException { 
    Scanner scan = new Scanner(new File("wordlist.txt")); 
    String s; 
    String words[] = new String[500]; 
    String word = JOptionPane.showInputDialog("Enter a word to search for"); 
    while (scan.hasNextLine()) { 
     s = scan.nextLine(); 
     int indexfound = s.indexOf(word); 
     if (indexfound > -1) { 
      JOptionPane.showMessageDialog(null, "Word was found"); 
     } else if (indexfound < -1) { 
      JOptionPane.showMessageDialog(null, "Word was not found"); 
     } 
    } 
} 

回答

0

代替String#indexOf使用String#matches方法是這樣的:

boolean matched = s.matches("\\b" + word + "\\b"); 

這將確保用戶輸入的單詞在包含單詞邊界的行中找到。

btw它不清楚爲什麼你聲明words一個500個元素的字符串數組,你沒有在任何地方使用它。

0

你說的那封信,你說的話,你到底在找什麼?

如果您搜索詞,您必須搜索詞邊界內的單詞:正則表達式java.util.regex.Pattern \ b,如anubhava所示。

您可以用} else {代替} else if (indexfound < -1) {,因爲java.lang.indexOf()當沒有找到時返回-1;否則,< -1從不發生。

1
if (indexfound>-1) 
{ 
    JOptionPane.showMessageDialog(null, "Word was found"); 
} 
else if (indexfound<-1) 
{ 
    JOptionPane.showMessageDialog(null, "Word was not found");} 
} 

這段代碼的問題是,indexFound可以等於-1,但不得低於-1。更改<運營商的==運營商。

一種替代

這是用於檢查是否存在於另一個String一個String相當一個模糊方法。在String對象中使用matches方法更合適。這裏是documentation

喜歡的東西:

String phrase = "Chris"; 
String str = "Chris is the best"; 
// Load some test values. 
if(str.matches(".*" + phrase + ".*")) { 
    // If str is [something] then the value inside phrase, then [something],true. 
} 
0

你 「否則,如果」 語句應該閱讀

} else if (indexfound == -1){ 

因爲IndexOf方法正好返回-1,如果沒有找到子串。

0

我在代碼中發現了一些令人困惑的事情。

  • 它看起來像你每個單詞輸出一次而不是整個文件一次。
  • 當你有一本字典時,你通常每行只有一個字,所以它會匹配或不匹配。它看起來像你(和大多數其他答案)試圖找到更長的字符串內的單詞,這可能不是你想要的。如果你搜索'ee',你不想在'啤酒'中找到它,對吧?

因此,假設字典是每行一個有效的單詞,並且您不想在整個字典中的任何位置找到該單詞,那麼這個簡單的代碼就可以實現。

import java.io.File; 
import java.io.FileNotFoundException; 
import java.util.Scanner; 

public class Main { 

    public static void main(String[] args) throws FileNotFoundException { 
     Scanner scanner = new Scanner(new File("wordlist.txt")); 
     String word = "Me"; 
     try { 
      while (scanner.hasNextLine()) { 
       if (scanner.nextLine().equalsIgnoreCase(word)) { 
        System.out.println("word found"); 
        // word is found, no need to search the rest of the dictionary 
        return; 
       } 
      } 
      System.out.println("word not found"); 
     } 
     finally { 
      scanner.close(); 
     } 
    } 
}