我想让“szSearch”读取WORDLIST.txt文件并检查用户的单词在文件中出现了多少次。
您要搜索什么词?long正在搜索文件...
单词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("\n\n--- File End ---");
}//end try catch finally`
}//end class
这是我尝试做的,但当我运行它,它说:
您正在搜索什么单词?long正在搜索文件...单词long在WORDLIST.txt文件中出现0次。
---文件结束---
1条答案
按热度按时间t40tm48m1#
试着用这段代码替换while,它可能需要一些调整,因为我没有测试代码,但是我认为逻辑解决了这个问题。