我想做的是让我的程序列出文本文件中的单词以及某个单词打印的次数。
例如,如果我的文本文件包含此内容。
hello my name is john hello my
输出将显示
hello 2
my 2
name 1
is 1
john 1
我已经这样做了,所以它打印单词数,但不打印每个单词的频率,我创建了一个 HashMap ,但在第 38 行收到运行时错误。任何帮助将不胜感激。
public class Mainstackquestion
{
public static void main(String args[])
{
if(args.length > 0)
{
for (String filename : args)
{
CheckFile(filename);
}
}
else
{
CheckFile("C:\\Users\\User\\Desktop\\files\\1.txt");
}
}
private static void CheckFile(String file)
{
Runnable tester = new WordCountstackquestion(file);
Thread t = new Thread(tester);
t.start();
}
}
这是我的另一个类
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Scanner;
public class WordCountstackquestion implements Runnable
{
private String filename;
public WordCountstackquestion(String filename)
{
this.filename = filename;
}
public void run()
{
int count = 0;
try
{
Scanner in = new Scanner(new File(filename));
while (in.hasNext())
{
in.next();
count++;
}
System.out.println(filename + " : " + count);
}
catch (FileNotFoundException e)
{
System.out.println(filename + " was not found.");
}
HashMap<String, Integer> map = new HashMap<String, Integer>();
{
Scanner in = null;
while (in.hasNext()) {
String word = in.next();
if (map.containsKey(word))
map.put(word, map.get(word) + 1);
else{
map.put(word, 1);
}
}
for (String word : map.keySet()) {
System.out.println(word + " " + map.get(word));
}
}
}
}
最佳答案
您必须合并两个循环:
while (in.hasNext())
{
String word = in.next();
if (map.containsKey(word))
map.put(word, map.get(word) + 1);
else{
map.put(word, 1);
}
count++;
}
System.out.println(filename + " : " + count);
因为如果使用两个循环,第一个循环将读取整个文件,并且指针位于文件末尾,因此在第二个循环中没有数据可读取,并且 in.hasNext()
返回 false。
更新 整个代码必须如下所示:
导入java.io.File; 导入 java.io.FileNotFoundException; 导入java.util.HashMap; 导入java.util.Scanner;
public class WordCountstackquestion implements Runnable {
private String filename;
public WordCountstackquestion(String filename) {
this.filename = filename;
}
public void run() {
int count = 0;
try {
HashMap<String, Integer> map = new HashMap<String, Integer>();
Scanner in = new Scanner(new File(filename));
while (in.hasNext()) {
String word = in.next();
if (map.containsKey(word))
map.put(word, map.get(word) + 1);
else {
map.put(word, 1);
}
count++;
}
System.out.println(filename + " : " + count);
for (String word : map.keySet()) {
System.out.println(word + " " + map.get(word));
}
} catch (FileNotFoundException e) {
System.out.println(filename + " was not found.");
}
}
}
关于java - 尝试计算文件中单词数列表时出现运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43654295/