[英]Java Text File Search
I have this method to search for a word in a text file but it constantly gives me back a negative result even tho the word is there?? 我有这种方法可以在文本文件中搜索单词,但是即使单词在那里,它也会不断带给我负面结果?
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");
}
It is because you are replacing the value of the indexfound
in your loop. 这是因为您要替换循环中的
indexfound
的值。 So if the last line does not contains the word, the final value of indexfound
will be -1. 因此,如果最后一行不包含单词,则
indexfound
的最终值为-1。
I would recommand: 我建议:
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");
}
Break the while
loop if the word is found 如果找到单词,则打破
while
循环
while (scan.hasNextLine()) {
s = scan.nextLine();
indexfound = s.indexOf(word);
if(indexFound > -1)
break;
}
Problem with the above code is - the indexFound
is getting overwritten. 上面的代码的问题是
indexFound
被覆盖。 Your code ONLY works FINE, if the word is present in the last line of the file. 如果文件的最后一行中包含单词,则您的代码仅能正常工作。
increament the indexfound in the while loop rather than indexfound = s.indexOf(word); 使while循环中的indexfound失去作用,而不是indexfound = s.indexOf(word);
give 给
while (scan.hasNextLine())
{
s = scan.nextLine();
if(s.indexOf(word)>-1)
indexfound++;
}
using the indexfound value you can also find number of occurance in the file. 使用indexfound值,您还可以找到文件中的出现次数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.