gpt4 book ai didi

java - 如何用java制作频率直方图

转载 作者:行者123 更新时间:2023-12-02 10:36:34 25 4
gpt4 key购买 nike

我正在尝试创建一个读取文件并打印出以下内容的代码:

  • 文件的行数
  • 每个字母出现的频率
  • 每个非字母字符的出现频率

我想为字母和数字的频率创建一个直方图,但我似乎找不到解决方案。如果有什么我希望输出看起来像这样:

A ***** - 5
B *** - 3
C ******* - 7

我的输出如下所示:

*********************
*********************
*********************
A 263
B 130
C 50

等等

最佳答案

这就是你完成任务的方式。正如您想要的那样,除了频率之外,它还会计算小写字母的数量并打印星星。

这是一般代码(paragraph 是包含文件内容的字符串):

int[] lettercount = new int[26];
for(int i = 0; i < 26; i++){
//Set every single number in the array to 0.
lettercount[i] = 0;
}

for(char s : paragraph.toCharArray()){
int converted = (int) s;
converted -= 97;
if(converted >=0 && converted <=25){
lettercount[converted] += 1;
}
}

//Print out the letter with the frequencies.
for(int i = 0; i < 26; i++){
char convertback = (char) (i+97);
String stars = "";
for(int j = 0; j < lettercount[i]; j++){
stars += "*";
}
System.out.println(convertback + " " + stars + " - " + lettercount[i]);
}

这应该适用于小写字母。如果您想要大写字母,lettercount[] 的长度应为 52 个元素。您还必须检查转换(在第二个for循环中),在减去97后是否为负数,如果是,则添加回58。

我希望这有帮助!如果您有任何问题,请在下面评论。

关于java - 如何用java制作频率直方图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53252568/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com