Как я могу получить переменную для чтения файла и проверить, сколько раз он содержит слово?JAVA

Программисты JAVA общаются здесь
Ответить
Anonymous
 Как я могу получить переменную для чтения файла и проверить, сколько раз он содержит слово?

Сообщение Anonymous »

Я хотел, чтобы «SZSearch» прочитал файл wordlist.txt и проверил, сколько раз в файле появляется слово пользователя. Так, например, < /p>
Какое слово вы ищете? long < /strong>
Поиск файла ...

слово long появляется 24 раза в файле wordlist.txt. < /p>
--- Конец файла --- < /p>
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
< /code>

Это то, что я пытался сделать, но когда я запускаю, он говорит: < /p>
Какое слово вы ищете? long < /strong>
Поиск файла ...
слово long появляется в 0 раз в файле wordlist.txt. < /p>
--- Конец файла --- < /p>

Подробнее здесь: https://stackoverflow.com/questions/751 ... ntains-a-w
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «JAVA»