我有这种方法可以在文本文件中搜索单词,但它不断地给我返回否定结果,即使该单词在那里?
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/