计数一直保持为零。我只是尝试阅读文本文件并查找单词,并将计数显示给用户。
我不知道它在哪里分崩离析。我认为是If语句,但不确定语法出错的地方。谢谢你的帮助!
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
import javax.swing.*;
public class TextSearchFromFile
{
public static void main(String[] args) throws FileNotFoundException
{
boolean run = true;
int count = 0;
//greet user
JOptionPane.showMessageDialog(null,
"Hello, today you will be searching through a text file on the harddrive. \n"
+ "The Text File is a 300 page fantasy manuscript written by: Adam\n"
+ "This exercise was intended to have the user enter the file, but since \n"
+ "you, the user, don't know which file the text to search is that is a \n"
+ "bit difficult.\n\n"
+ "On the next window you will be prompted to enter a string of characters.\n"
+ "Feel free to enter that string and see if it is somewhere in 300 pages\n"
+ "and 102,133 words. Have fun.",
"Text Search",
JOptionPane.PLAIN_MESSAGE);
while (run)
{
try
{
//open the file
Scanner scanner = new Scanner(new File("An Everthrone Tale 1.txt"));
//prompt user for word
CharSequence findWord = JOptionPane.showInputDialog(null,
"Enter the word to search for:",
"Text Search",
JOptionPane.PLAIN_MESSAGE);
count = 0;
while (scanner.hasNext())
{
if ((scanner.next()).contains(findWord))
{
count++;
}
} //end search loop
//output results to user
JOptionPane.showMessageDialog(null,
"The results of your search are as follows: \n"
+ "Your String: " + findWord + "\n"
+ "Was found: " + count + " times.\n"
+ "Within the file: An Ever Throne Tale 1.txt",
"Text Search",
JOptionPane.PLAIN_MESSAGE);
} //end try
catch (NullPointerException e)
{
JOptionPane.showMessageDialog(null,
"Thank you for using the Text Search.",
"Text Search",
JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
} //end run loop
} // end main
} // end class
编辑: 再次需要帮助。教师改变了项目的参数,现在我需要找到像#34; th"或" en"并计算那些。
这种感觉超出了他所教导的范围,我不知道如何做到这一点。我已经谷歌搜索了,直到我不能谷歌了。
答案 0 :(得分:0)
您必须向File
提供一个Scanner
对象才能阅读该文件,目前所有搜索结果都在字符串中“Everthrone Tale 1.txt”
Scanner scanner = new Scanner(new File("An Everthrone Tale 1.txt"));
要搜索一个单词,你需要这样做:
while (scanner.hasNext())
{
if (findWord.equals(scanner.next()))
{
count++;
}
}
如果您要执行 case-insensitive
搜索,请使用String#equalsIgnoreCase
代替String#equals
希望这有帮助