[英]Getting letters from an array
我有一個程序可以對字母在故事中出現的次數進行分類和計數。 我遇到的一個問題是,我需要打印字母以及排序時出現的次數。
if (line == null) break; //check for end of file before doing anything
line=line.toLowerCase();
for (int i = 0 ; i < line.length(); i++ ) {
letter = line.charAt(i);
int num = (int)letter;
num-=96;
if(num>=1 && num<=26) alpha[num]++;
}
for(int j=1; j<=26; j++) System.out.println((char)(j+64) +" = "+alpha[j]);
int[] minArr = new int[6];
int[] maxArr = new int[6];
Arrays.sort(alpha);
// System.out.print("There are "+max+" and "+min);
for(int n=1;n<=5;n++) {
System.out.println("is the highest with "+alpha[alpha.length-n]);
System.out.println("is the lowest with "+alpha[n]);
// int max = alpha.length-n;
// System.out.println((char)(min+64)+" has the least number of letters"
}
有什么辦法可以獲取帶有其值的排序字母?
您是否考慮過使用Map<String,Integer>
存儲您的字符計數對?
類似於以下內容:
SortedMap <String, Integer> alphaMap = new TreeMap<String, Integer>() {};
for (int i = 0 ; i < line.length(); i++ ) {
String letter = String.valueOf(line.charAt(i));
if (alphaMap.containsKey(letter)){
alphaMap.get(letter)++;
} else {
alphaMap.put(letter, 0);
}
}
然后,您將獲得按字母順序排列的字符計數對映射。 然后,您可以使用該樹找到最大值和最小值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.