[英]Getting letters from an array
I have a program that sorts and counts the number of occurences that a letter appears in a story. 我有一个程序可以对字母在故事中出现的次数进行分类和计数。 The one issue I have is that I need to print the letter and the number of times it occurs while sorted. 我遇到的一个问题是,我需要打印字母以及排序时出现的次数。
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"
}
Is there a way I am able to get the sorted letters with their values? 有什么办法可以获取带有其值的排序字母?
Have you considered using a Map<String,Integer>
to store you char-count pairs? 您是否考虑过使用Map<String,Integer>
存储您的字符计数对?
Something along the lines of: 类似于以下内容:
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);
}
}
You then have a map of your char-count pairs that is ordered by letter. 然后,您将获得按字母顺序排列的字符计数对映射。 You can then use this tree to find you max and min values. 然后,您可以使用该树找到最大值和最小值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.