简体   繁体   English

字母频率数组,将int转换为char

[英]Letter frequency array, converting int to char

My code below prints out a letter frequency table (number of letter occurances in a string) that is inputted from a scanner class. 我下面的代码打印出从扫描仪类输入的字母频率表(字符串中字母出现的次数)。 I Have everything working correctly except the last bit. 除了最后一点,我一切正常。 When executed, the table displays letters az and the number of occurrences except for the last method LargestLength() method. 执行时,该表显示字母az和出现的次数,除了最后一个方法LargestLength()方法外。 Since my array 'score' uses int[26], instead of using az it uses ints 0-25. 由于我的数组'score'使用int [26],因此使用int 0-25代替了az。 (0=A, 1=B, etc.) As of now my LargestLength method only displays the number (instead of the letter) which comes up the most but does not count the number of occurrences. (0 = A,1 = B,等等。)到目前为止,我的LargestLength方法仅显示出现次数最多的数字(而不是字母),但不计算出现的次数。

For example, If my string were to be "Hello", l shows up most frequently so i would like it to display, "Most Frequent: l 2" but with my code it displays "Most Frequent: 11" (11 = L). 例如,如果我的字符串是“ Hello”,则l出现频率最高,因此我希望它显示“ Most Frequent:l 2”,但是对于我的代码,其显示“ Most Frequent:11”(11 = L) 。 How would I go about fixing this? 我将如何解决这个问题?

Profile Class. 配置文件类。

public class LetterProfile {
  int score[] = new int [26];

   public void countChars (String s) {
    s = s.toLowerCase();
    char a = 'a';
    for (int i = 0; i < s.length(); i++) {
      int next = (int)s.charAt(i) - (int) a;
      if ( next< 26 && next >= 0)
        score[next]++;

    }
 }

    public int largestLength() { 
      int largest = 0;
      int largestindex = 0;
      for(int a = 0; a<26; a++) {
        if(score[a] > largest) {
        largest = score[a];
        largestindex = a ;


      }
      }
      return (char) largestindex;
    }

    public void printResults() {
       largestLength();

       for (int i = 0; i < score.length; i++) {
    System.out.println( (char)(i+97) + ": " + score[i]);
       }
  System.out.println(("Most Frequent") + (": ") + largestLength());
    }
}

A bit of a confusing explanation but any help would be appreciated. 有点混乱的解释,但任何帮助将不胜感激。

If my string were to be "Hello", l shows up most frequently so i would like it to display, "Most Frequent: l 2" but with my code it displays "Most Frequent: 11" (11 = L). 如果我的字符串是“ Hello”,则l出现频率最高,因此我希望它显示“ Most Frequent:l 2”,但是对于我的代码,它显示“ Most Frequent:11”(11 = L)。 How would I go about fixing this? 我将如何解决这个问题?

Simple: String.valueOf((char)(number + 'A')); 简单: String.valueOf((char)(number + 'A'));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM