[英]How can I get a variable to read a file and check how many times it contains a word?
I wanted "szSearch" to read the WORDLIST.txt file and check how many times the user's word appears in the file.我想让“szSearch”读取 WORDLIST.txt 文件并检查用户的单词在文件中出现了多少次。 So for example,
例如,
What word are you searching for?您要搜索什么词? long Searching the file...
长搜索文件...
The word long appears 24 times in the file WORDLIST.txt.单词 long 在文件 WORDLIST.txt 中出现了 24 次。
--- File End --- --- 文件结束 ---
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("\n\n--- File End ---");
}//end try catch finally`
}//end class
This is what I tried doing but when I run it, it says:这是我尝试做的,但是当我运行它时,它说:
What word are you searching for?您要搜索什么词? long Searching the file... The word long appears 0 times in the file WORDLIST.txt.
long正在搜索文件... 单词 long 在文件 WORDLIST.txt 中出现 0 次。
--- File End --- --- 文件结束 ---
Try replacing the while you have with this block of code, it probably requires some tweaking as I didn't test the code, but the logic I think solves it.尝试用这段代码替换 while,它可能需要一些调整,因为我没有测试代码,但我认为逻辑可以解决它。
while ((strCurrentLine = objReader.readLine ())! = null) {
List<String> words = Arrays.asList(strCurrentLine.split(" "));
iCount += words.stream().hasMatch(w -> w.equals(szWord)).count();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.