Я пытаюсь написать программу, которая читает из текстового файла, ищет слово и подсчитывает, сколько экземпляров этого слова находится в файле.Поиск и подсчет определенного слова в текстовом файле Java
Это будет пример вывода:
*Enter the name of the text file:
input.dat
Enter the word you're searching for in text file:
that
The word "that" appeared 3 times in the file input.dat*
EDIT
Мой файл данных находится в C: \ Users \ User1 \ Documents \ NetBeansProjects \ WordCounter его назвали суперфиша и содержит слова:
супер супер свежие супер рыба ужин мучиться sooper foosh Супер SupeR SupeR
Это выход я получаю после ввода моих входов
*run: Enter the name of the text file: superfish.txt Enter the word you are searching for in the text file: super The word "super" appeared 0 times in the file superfish.txt*
Это код, который я написал до сих пор, основная проблема заключается в том, что count возвращает 0 всякий раз, когда он запускается.
Я искал решения повсюду, и я просто не могу понять, что я делаю неправильно.
import java.util.Scanner;
import java.io.*;
public class WordCounter
{
public static void main(String[] args) throws IOException
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the name of the text file:");
String name = keyboard.nextLine();
File file = new File(name);
System.out.println("Enter the word you are searching for in the text file:");
String word = keyboard.nextLine();
try
{
System.out.println("The word \""+word+"\" appeared "+ searchCount(file,word) + " times in the file "+ file);
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
}
public static int searchCount(File fileA, String fileWord) throws FileNotFoundException
{
int count = 0;
Scanner scanner = new Scanner(fileA);
while (scanner.hasNextLine())
{
String nextWord = scanner.next();
System.out.println(nextWord);
if (nextWord.equalsIgnoreCase(fileWord))
count++;
}
//End While
return count;
}
}
'Я просто не могу понять, что я делаю wrong' вы не сравниваете строку' fileWord' в файл контента в любом месте – silentprogrammer
Это не похоже на то, что вы вообще что-то делаете – ControlAltDel
Только что отредактировал его, случайно оставил заявление if при резке и вставке здесь. – Ariver