Java文本文件搜索

时间:2013-04-09 09:59:42

标签: java search text

我有这种方法在文本文件中搜索一个单词,但是即使这个单词存在,它也会不断地给我一个否定的结果?

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

3 个答案:

答案 0 :(得分:1)

这是因为您正在替换循环中indexfound的值。因此,如果最后一行不包含该单词,则indexfound的最终值将为-1。

我建议:

public static void Option3Method(String dictionary) throws IOException {
    Scanner scan = new Scanner(new File(dictionary));
    String s;
    int indexfound = -1;
    String word1 = JOptionPane.showInputDialog("Enter a word to search for");
    String word = word1.toLowerCase();
    word = word.replaceAll(",", "");
    word = word.replaceAll("\\.", "");
    word = word.replaceAll("\\?", "");
    word = word.replaceAll(" ", "");
    while (scan.hasNextLine()) {
        s = scan.nextLine();
        indexfound = s.indexOf(word);
        if (indexfound > -1) {
            JOptionPane.showMessageDialog(null, "Word found");
            return;
        }
    }
    JOptionPane.showMessageDialog(null, "Word not found");
}

答案 1 :(得分:0)

如果找到单词,则中断while循环

while (scan.hasNextLine()) {
  s = scan.nextLine();
  indexfound = s.indexOf(word);
  if(indexFound > -1)
     break;
}

上述代码存在问题 - indexFound被覆盖。 如果该单词出现在文件的最后一行中,则您的代码仅适用于FINE。

答案 2 :(得分:0)

在while循环中增加indexfound而不是indexfound = s.indexOf(word);

while (scan.hasNextLine()) 
   {
    s = scan.nextLine();
    if(s.indexOf(word)>-1)
        indexfound++; 

    }

使用indexfound值,您还可以找到文件中出现的次数。