我一直在尝试编写一个程序来读取文本文件、搜索单词并计算该单词在文件中出现的次数。
这将是一个示例输出:
*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*
编辑
我的数据文件位于 C:\Users\User1\Documents\NetBeansProjects\WordCounter 它被命名为 superfish 并包含以下文字:
super 棒 极好的 新鲜的 极好的 鱼 晚餐 时尚 傻瓜 嘘 极好的 极好的 super
这是我输入输入后得到的输出
*运行:
输入文本文件的名称:
super 鱼.txt
在文本文件中输入您要搜索的词:
极好的
“super”一词在文件 superfish.txt* 中出现了 0 次*
这是我到目前为止编写的代码,主要问题是每次运行时 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;
}
}
最佳答案
searchCount
有两个大问题:
- 它实际上不算数:-)
- 它检查扫描仪是否有另一行,但只读取一个单词。
这是修复这两个问题的 searchCount
的修订版:
public static int searchCount(File fileA, String fileWord) throws FileNotFoundException
{
int count = 0;
fileWord = fileWord.trim();
Scanner scanner = new Scanner(fileA);
while (scanner.hasNext()) // Fix issue #2
{
String nextWord = scanner.next().trim();
if (nextWord.equals(fileWord)) { // Fix issue #1
++count;
}
}
//End While
return count;
}
关于java - 搜索和计算文本文件 Java 中的特定单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29827718/