我是从一个朋友那里被引导到这个网站的。目标是读取txt文件中的前100个字符串,计算这些单词出现的次数并打印出来。事先非常感谢。我在代码方面做得很好,但由于某种原因,这让我很困惑。
import java.util.Arrays;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Program6 {
public static void main(String[] args) throws FileNotFoundException {
WordAnalysis a = new WordAnalysis();
a.ReadFile();
}}
class WordAnalysis{
String[] coun = new String[1000];
int[] ana = new int[100];
void ReadFile() throws FileNotFoundException {
Scanner read = new Scanner(new File("myths.txt"));
int[] ana = new int[100];
String coun = new String();
String word=null;
while(read.hasNext()) {
word = read.next();
String[] arrWord = word.split(" ");
}
}
}
程序:
- 1:通过nextLine()从扫描仪读取行[0,99]
- 2:用另一个扫描仪分割行,并使用next()获取每个单词。或者,也可以使用拆分
- 3:将每个单词放在HashMap(String,Integer)中,其中String是单词,Integer是它出现的次数
- 4:遍历HashMap并打印出键、值对
检查一下,这里我使用了一个映射来保持字数。
int count = 0;
HashMap<String, Integer> wordCntMap = new HashMap();
while (read.hasNext()) {
count++;
word = read.next();
String[] arrWord = word.split(" ");
if (count == 100) {
break;
}
for (String str : arrWord) {
Integer num = wordCntMap.get(str);
if (num == null) {
wordCntMap.put(str, new Integer(1));
} else {
wordCntMap.put(str, num + 1);
}
}
}
System.out.println("Word Count " + wordCntMap);
欢迎来到Stack Overflow,这里没有答案太愚蠢,没有评论太轻率。
然而,很明显,您还没有完成这段代码的编写。:-)
现在你已经在arrWord中找到了你的单词,你需要开始使用某种结构,让你能够跟踪每个单词以及它被看到的次数。
有很多容器允许您使用字符串作为键,使用整数作为值。为了你的目的,你使用哪一个并不重要。
对于arrWord中的每个单词,看看你是否能在你的结构中找到它(Dictionary、Hashmap等等)。如果找不到"word",请插入[word,1]的新条目。如果你能找到单词,那么递增你找到的计数器。
完成后,您所需要做的就是打印出结构中每个条目的键值对。
啊!