Java 文本文件搜索

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

最佳答案

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

关于Java 文本文件搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15898926/

相关文章:

swift - 为 Siri 创建监听器

java - 如何从两个GPS坐标计算方向的角度

android - 在android中实现搜索

javascript - 如何使用JS改变网页上所有文字的颜色?

mysql - 尽管有行继承,(快速)搜索

vb.net - 滚动到 Datagridview 选定的行

text - 如何强制 Mercurial (hg) 将文件视为二进制文件?

java - 当应用程序集群时在两个 JVM 之间共享数据

java - 设置读取器、解码器和消费者线程

java - 在提交按钮内定义时如何获取 wicket id 的范围