public class Try{
public static void main (String args[]) throws IOException {
BufferedReader in = new BufferedReader(new FileReader("Try.txt"));
Scanner sc = new Scanner(System.in);
System.out.print("Enter the subtring to look for: ");
String Word=sc.next();
String line=in.readLine();
int count =0;
String s[];
do
{
s=line.split(" ");
for(int i=0; i < s.length; i++)
{
String a = s[i];
if(a.contains(Word))
count++;
}
line=in.readLine();
}while(line!=null);
System.out.print("There are " +count+ " occurences of " +Word+ " in ");
java.io.File file = new java.io.File("Try.txt");
Scanner input = new Scanner(file);
while(input.hasNext())
{
String word = input.nextLine();
System.out.print(word);
}
}
}
我的程序的预期用途是要求用户输入将在文本文件中检查的特定单词并且是否存在它会计算用户输入的单词在文本文件中出现的次数。到目前为止,我的程序只能搜索一个单词。如果我尝试用空格分隔两个单词,则只会搜索第一个单词并计算其出现次数。有关如何搜索多个单词的任何提示?询问单词并检查其在文本文件中的出现次数
程序中的什么逻辑会让你觉得它会搜索多个单词?你只有一个'if(a.contains(Word))'行和一个计数器。您需要为每个输入的单词保留计数器。 – KevinO
'String Word = sc.next();'这意味着你正在读一个名为'Word'的字符串。即使你要改变这条线,你也需要做更多的事情来确保你要找的两个词不相邻。您也可以运行调试器来检查“Word”的内容,看看它是否只包含一个值。请参阅[Scanner.next()](https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#next()) –