我正在尝试为“list.txt”文档中的特定单词创建一个基本的单词计数器。我现在使用的代码没有扫描“Customer”,即使 Customer 已经在 word 文档中出现过几次,我已经尝试创建一个值为“Customer”的 String 变量,但这也没有用, 任何人都可以纠正我出错的地方吗?
static int totalContracts() throws FileNotFoundException
{
Scanner scannerInput = new Scanner("list.txt");
int count = 0;
while (scannerInput.hasNext())
{
String nextWord = scannerInput.next();
System.out.println(nextWord);
if (nextWord.equals("Customer"))
{
count++;
}
}
return count;
}
最佳答案
您没有打开文件。
Scanner scannerInput = new Scanner(new File("list.txt"));
如果您使用 new Scanner("list.txt")
,它只会扫描文本“list.txt”。
关于java - 如何计算 Java 中 txt 文件中特定单词的出现次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48160957/