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()) –