【问题标题】:Unable to get my Histogram to Count Correctly无法让我的直方图正确计数
【发布时间】: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()]++;
    }
}

【问题讨论】:

    标签: java histogram


    【解决方案1】:

    解决这个问题,

    for (int p=0;p<histogram.length;p++)
    {
        newHistogram[p]=histogram[p]; //swapped around
    }
    

    还有这个,

    if (word.length() >= histogram.length)
    {
    ....
    }
    else // introduced
    if (word.length() < histogram.length){
            histogram[word.length()]++;
    }
    

    【讨论】:

    • 只是一个简单的问题,为什么我需要 else?我认为它只会看到 word.length() 小于 histogram.length() 并转到那个条件。但显然我的逻辑是有缺陷的。
    • 如果进入第一个 if 块,(新的)直方图长度将始终为word.length()+1,因此它将多余地进入第二个块。通过使用if-else,您正在“冻结”对您想要使用的原始直方图的检查,因为当 CPU 到达代码中的此连接点时,决定输入什么 if 块只会发生一次。
    【解决方案2】:

    编辑(感谢 mockinterface): 您需要更改复制新直方图的 for 循环:

    for (int p=0;p<histogram.length;p++){
            newHistogram[p] = histogram[p];
    }
    

    所以你将旧的直方图复制到新的直方图中。

    您需要将第二个if 条件更改为else

    如果单词的长度大于直方图的长度:

    在第一个if 中,您创建一个长度为word.length+1 的新直方图,将旧直方图复制到那里并增加histogram[word.lenth]

    然后您达到第二个if 条件,现在histogram.length 大于word.length(因为您在之前的if 中更改了它)所以您再次增加histogram[word.lenth]

    【讨论】:

    • 这还不够——复制到 newHistogram 也是错误的。
    猜你喜欢
    • 1970-01-01
    • 2020-02-20
    • 2020-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-11
    • 1970-01-01
    • 2021-07-25
    相关资源
    最近更新 更多