0

我有这种方法可以在文本文件中搜索一个词,但它不断给我一个否定的结果,即使这个词在那里?

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");
 }
4

3 回答 3

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");
}
于 2013-04-09T10:03:03.077 回答
0

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

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

上面代码的问题是 -indexFound被覆盖了。如果该单词出现在文件的最后一行,则您的代码只能正常工作。

于 2013-04-09T10:04:26.967 回答
0

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

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

    }

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

于 2013-04-09T10:08:43.300 回答