Java文本文件搜索

问题描述:

我有这种方法来搜索文本文件中的一个单词,但它不断给我回负面的结果,即使这个单词在那里?Java文本文件搜索

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

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

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

    } 

使用indexfound值还可以查找文件中次数的数量。

这是因为您正在替换循环中的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"); 
} 

打破while循环,如果这个词是发现

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

问题与上面的代码是 - indexFound被覆盖掉了。 如果该文件的最后一行中出现该字,则您的代码只能使用FINE。