2013-04-07 136 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(); 
     } 
    } 
}