我想要"读取WORDLIST.txt文件,并检查用户的单词在文件中出现了多少次。例如,
你在找什么词?搜索文件…
单词long在文件WORDLIST.txt中出现了24次。
——文件结束——
public static void main(String[] args)
{
//creating scanner objects which will be used to read in the file
FileReader file = null;
BufferedReader br = null;
//declaring variables and assigning values
Scanner szKeyboard = new Scanner (System.in);
String szWord = "";
String szSearch;
int iCount = 0;
try
{
//open the file WORDLIST.txt using the Scanner and File classes
//File object used to open and store the file
//Scanner object will be used to read through the file object
file = new FileReader("WORDLIST.txt");
//needed for methods
br = new BufferedReader(file);
//ask the user what word they're searching for
System.out.print("What word are you searching for? ");
szWord = szKeyboard.nextLine();
System.out.println("Searching the file...");
szSearch = br.readLine();
//method to count how many times that word occurs in the WORDLIST.txt file
while (szSearch.contains(szWord))
{
iCount = iCount + 1;
}
System.out.println("The word " + szWord + " appears " + iCount + " times in the file WORDLIST.txt.");
}//end try
catch (Exception e)
{
System.out.println("Error - Writing to File: " + e);
}//end catch
finally
{
//close scanner
szKeyboard.close();
//finally runs regardless of wheter the try has worked
//the aim of a finally is to tidy up any loose ends
//if the contents within read is not equal to nothing i.e. it was possible to open and read
//close the file (try) if the file was not loaded catch the exception IOException
try
{
br.close();
`your text` }
catch(IOException e)
{
System.out.println("Error - Closing BufferReader: " + e);
}
try
{
file.close();
}
catch(IOException e)
{
System.out.println("Error - closing FileReader: " + e);
}
System.out.println("nn--- File End ---");
}//end try catch finally`
}//end class
这就是我尝试做的,但是当我运行它时,它说:
你在找什么词?搜索文件…单词long在文件WORDLIST.txt中出现了0次。
——文件结束——
尝试用此代码块替换while,这可能需要一些调整,因为我没有测试代码,但我认为逻辑解决了它。
while ((strCurrentLine = objReader.readLine ())! = null) {
List<String> words = Arrays.asList(strCurrentLine.split(" "));
iCount += words.stream().hasMatch(w -> w.equals(szWord)).count();
}