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

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

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

int [ ]lettersLabels = new int [26];
        int [ ]lettersFrequency = new int [26];
        String line;

//initialize arrays
        letterLabels = 0;
        lettersFrequency = 0;

        Scanner sc = new Scanner(constitution);

         while(sc.hasNextLine())
         {
            line = sc.nextLine();
            line = sc.toLowerCase();
            char[] characters = line.toCharArray();

            for (int i = 0; i< characters.length ; i++) 
            {
                if((characters[i] >='a') && (characters[i]<='z'))
                {
                     lettersLabels[characters[i] -'a' ]++;
                }
            }
         }

         for (int i = 0; i < 26; i++) 
         {
          lettersFrequency = 'a' + [characters[i] -'a' ]++;
          lettersFrequency = lettersFrequency / 100;
          System.out.println(lettersFrequency);
         }
sqxo8psd

sqxo8psd1#

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

int [ ]lettersLabels = new int [26];
        int [ ]lettersFrequency = new int [26];
        String line;

        int totalLetter =0; // needed to calculate %

// No need to initialize, it's already initialized with 0 values.
// remove those lines.
//initialize arrays
//        letterLabels = 0;
//        lettersFrequency = 0;

        Scanner sc = new Scanner(constitution);

         while(sc.hasNextLine())
         {
            line = sc.nextLine();
            // need to lower case the current line
            line = line.toLowerCase();
            char[] characters = line.toCharArray();

            for (int i = 0; i< characters.length ; i++) 
            {
                if((characters[i] >='a') && (characters[i]<='z'))
                {
                     // lets count the letter frequency.
                     totalLetter++;
                     lettersFrequency[characters[i] -'a' ]++;
                }
            }
         }

         // get rid of divide by zero exception
         if(totalLetter ==0) totalLetter =1;

         for (int i = 0; i < 26; i++) 
         {
          char ch = 'a'+i;
          // let's count the parentage of each letter.
          double parcentage = (lettersFrequency[i]*100.00)/totalLetter;
          System.out.println("parcentage of "+ ch+ " is: " +lettersFrequency +"%");
         }
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 数组。
希望这能奏效!

相关问题