【发布时间】:2015-06-14 11:23:14
【问题描述】:
考虑到我们有txt 文件,我们想知道txt 的每个单词出现了多少次。我使用了以下代码,但它不起作用。它给出所有值 1 。
首先,我阅读txt 文件并将每个单词写在单独的行中。同时,我将它们放入Array List。然后,我读取txt 文件的第一行并获取数组列表的第一个元素并与整个txt 文件进行比较。如果出现任何情况,将显示出现次数的数组增加一。然后获取第二个 Array List 项,依此类推,直到到达 Array List 的末尾。
private static void count(String text) throws FileNotFoundException, IOException {
FileOutputStream thewords=new FileOutputStream(Check);
ArrayList<String> keyArrayList=new ArrayList<String>();
int countWord=0;
StringTokenizer tokenizer =new StringTokenizer(text) ;
while(tokenizer.hasMoreTokens())
{
String nextWord=tokenizer.nextToken();
keyArrayList.add(nextWord);
thewords.write(nextWord.getBytes());
thewords.write(System.getProperty("line.separator").getBytes());
countWord++;
}
int[] numbOfOccurance=new int[countWord];
BufferedReader br=new BufferedReader(new FileReader(Check));
String readline;
for(int loopIndex=0;loopIndex<countWord;loopIndex++)
{
readline=br.readLine();
String test=keyArrayList.get(loopIndex);
if(test.equals(readline))
{
numbOfOccurance[loopIndex]++;
}
}
【问题讨论】:
-
使用 hashmap
其中 string 将是您的单词,而 Integer 将是您的计数。 -
@Pratik 在哪一行?
-
旁注:来自javadoc,StringTokenizer 是一个遗留类,出于兼容性原因保留,但不鼓励在新代码中使用它。建议任何寻求此功能的人使用 String 的 split 方法或 java.util.regex 包。
-
读取文件的每个单词.....检查它是否包含在哈希表中,然后使用您的单词作为键从 hashmap 中计数,将计数增加 1,然后再次使用您的单词放入作为一把钥匙。如果它不包含在哈希映射中,则使用您的单词作为键和 1 作为计数插入哈希映射。
-
@sp00m 所以你是说这个问题是为了
StringTokenizer而引起的吗?
标签: java arrays string file arraylist