【发布时间】:2014-02-02 02:34:11
【问题描述】:
我必须计算文本文件中字符串的长度并找出它们出现的频率。我可以计算长度,但我的频率计数器总是关闭,我不知道为什么。
假设我要传入一个包含以下文字的文件: 再膨胀, 错误, 停产, 胃胀气,和 齿条
我的程序注册了 2 个长度为 8 的字符串实例(正确)和 2 个长度为 16 的字符串实例(这是错误的,只有一个),它甚至无法识别 10 个字母的单词和 9 个字母的单词。我们也不允许使用 ArrayList,所以我们必须自己调整数组的大小。
这是我的代码:
int [] histogram = new int[0];
// while loop to read all words into your String[]
// and update all the freq counter for word lengths
while(infile.ready())
{
String word = infile.readLine();
if (word.length() >= histogram.length){
int [] newHistogram = new int [word.length()+1];
for (int p=0;p<histogram.length;p++){
histogram[p]=newHistogram[p];
}
newHistogram[word.length()]++;
histogram=newHistogram;
}
if (word.length() < histogram.length){
histogram[word.length()]++;
}
}
【问题讨论】: