我正在迭代一个文件,并获得每个单词中的字符数。当我找到每个单词的长度时,它会将字符数的int值放入数组索引位置。我不知道为什么或者怎么解决这个问题。然后,我甚至尝试重新迭代数组,并将每个int除以它的索引位置,但我不明白为什么我总是得到一个/ by 0异常。下面是我的代码。我使用的txt文件有一个两个字母的单词和两个三个字母的单词。输出2个字符的单词频率为2(应为1),3个字符的单词的频率为6(应为2)。对于这个赋值,我们只需要计算小于23个字符的所有单词的频率,并将以上所有23个字符分组到最后一个数组索引位置。下面是我的代码。任何帮助都将不胜感激。
private final int WORDLENGTH = 23;
private int[] wordLengthCount = new int [WORDLENGTH];
while (token.hasMoreTokens()){
token1 = token.nextToken();
for (int t = 0; t<token1.length(); t++){
wordLengthCount[token1.length()-1]++;
}发布于 2013-07-16 12:13:05
此处的代码
token1 = token.nextToken(); //Getting your token
for (int t = 0; t<token1.length(); t++) //For each character in token
{
wordLengthCount[token1.length()-1]++; //Increment count array
}正在递增String token1中字符数的计数数组。因此
1 * 2 character word = 2
2 * 3 character word = 6这里不需要for循环,只需在while循环中执行此操作
token1 = token.nextToken(); //Get token
wordLengthCount[token1.length()-1]++; //Increment your count array发布于 2013-07-16 12:12:08
while(token.hasMoreTokens()){
token1 = token.nextToken();
wordLengthCount[token1.length()-1]+=1;
}您不需要为每个标记遍历每个字符。只需引用数组中由所检查单词中的字母数引用的索引即可。
所以在这里你会看到一个3个字母的单词:
wordLengthCount[3 -1] +=1;
//so wordLengthCount[2] = 1 now或者是2个字母的单词:
wordLengthCount[2 -1] +=1;
//so wordLengthCount[1] = 1 now.如果您想知道字符数,可以通过将您正在检查的元素的索引乘以该索引的值来获得它们,如下所示:
//this will give you number of 3 letter word characters in file.
wordLengthCount[2] *= 3;
//or more useful, print out all frequencies and the number of characters in file
//which contributed to frequency
for(int i=0;i<wordLengthCount.length;i++){
System.out.println("Frequency for "+(i+1)+" letter words = "
+wordLengthCount[i]+", characters = "+(wordLengthCount[i]*(i+1)));
}https://stackoverflow.com/questions/17667820
复制相似问题