java—我试图使用扫描仪计算文档中每个字母的百分比,但我不知道如何正确地计算和显示它

oo7oh9g9  于 2021-07-06  发布在  Java
关注(0)|答案(2)|浏览(349)

首先我上传了我正在使用的文件,宪法。然后,我创建了两个数组,一个用来计算字母表的长度,另一个用来计算频率。我创建了一个while循环来读取文档中的每一行并计算每一个字母的频率,我只是不知道如何计算每个字母占每个字母的百分比,因为在我将它放入条形图之后。

  1. int [ ]lettersLabels = new int [26];
  2. int [ ]lettersFrequency = new int [26];
  3. String line;
  4. //initialize arrays
  5. letterLabels = 0;
  6. lettersFrequency = 0;
  7. Scanner sc = new Scanner(constitution);
  8. while(sc.hasNextLine())
  9. {
  10. line = sc.nextLine();
  11. line = sc.toLowerCase();
  12. char[] characters = line.toCharArray();
  13. for (int i = 0; i< characters.length ; i++)
  14. {
  15. if((characters[i] >='a') && (characters[i]<='z'))
  16. {
  17. lettersLabels[characters[i] -'a' ]++;
  18. }
  19. }
  20. }
  21. for (int i = 0; i < 26; i++)
  22. {
  23. lettersFrequency = 'a' + [characters[i] -'a' ]++;
  24. lettersFrequency = lettersFrequency / 100;
  25. System.out.println(lettersFrequency);
  26. }
sqxo8psd

sqxo8psd1#

在这里,我用描述修复了一些错误,请参见代码注解以获取解释:

  1. int [ ]lettersLabels = new int [26];
  2. int [ ]lettersFrequency = new int [26];
  3. String line;
  4. int totalLetter =0; // needed to calculate %
  5. // No need to initialize, it's already initialized with 0 values.
  6. // remove those lines.
  7. //initialize arrays
  8. // letterLabels = 0;
  9. // lettersFrequency = 0;
  10. Scanner sc = new Scanner(constitution);
  11. while(sc.hasNextLine())
  12. {
  13. line = sc.nextLine();
  14. // need to lower case the current line
  15. line = line.toLowerCase();
  16. char[] characters = line.toCharArray();
  17. for (int i = 0; i< characters.length ; i++)
  18. {
  19. if((characters[i] >='a') && (characters[i]<='z'))
  20. {
  21. // lets count the letter frequency.
  22. totalLetter++;
  23. lettersFrequency[characters[i] -'a' ]++;
  24. }
  25. }
  26. }
  27. // get rid of divide by zero exception
  28. if(totalLetter ==0) totalLetter =1;
  29. for (int i = 0; i < 26; i++)
  30. {
  31. char ch = 'a'+i;
  32. // let's count the parentage of each letter.
  33. double parcentage = (lettersFrequency[i]*100.00)/totalLetter;
  34. System.out.println("parcentage of "+ ch+ " is: " +lettersFrequency +"%");
  35. }
展开查看全部
f0ofjuux

f0ofjuux2#

百分比为 ratio * 100 ( 1/2 = 0.5 = (0.5 * 100)% = 50% ),这里的比率是 lettersLabels[i] / totalLetters . 所以,为了找到百分比,你只需要 lettersFrequency[i] = (double) lettersLabels[i] / (double) totalLetters * 100; . 所以,你可能需要一个变量 totalLetters 开始数字母的数目。
您的代码中有一个错误,即使用初始化数组 0 . 您已经用初始化了数组 int[] arr = new int[26]; ,因此您不需要这两行,因为使用 int 是错误的类型。另外,在设置 lettersFrequency 你需要指定索引,比如 lettersFrequency[i] ,而不是使用 characters 当获取字符超出范围时,则必须使用 letterLabels 数组。
希望这能奏效!

相关问题