我想要做的是让我的程序列出文本文件中的单词以及某个单词打印出多少次。尝试计算时运行时错误列出文件中的字数
因此,例如,如果我的文本文件包含此。
你好我的名字是约翰·你好我
输出将显示
你好2
我2
名1
是1
约1
所以它打印的字的数目,但每个字的不是频率我已经做到了,我创建了一个哈希表,但我发现上线运行时错误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));
}
}
}
}
阅读Java命名约定。它说方法名称应该以小写字符开头 – Jens
您已经阅读了这个循环中的完整文件:'while(in.hasNext()){in.next(); count ++; }',所以其他循环将不会运行 – Jens
它是用C编写的C代码。双方都不好。 – zubergu