我正在尝试制作一个程序来计算用户输入的短语中字母的所有实例。例如,短语“Hello”将输出“h: 1”、“e: 1”、“l: 2”、“o: 1”
。
我已经想出了如何查找和计算除 "a"
之外的所有字母。当我多次将 "a"
与自身进行比较时,它每次都会返回不同的值(因此短语 "aaaa"
会给我 a: 1, b: 1, c: 1, d: 1
)
这是我正在使用的代码:
int[] countLetter = new int[26];
char[] alphabet = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
phrase = phrase.toLowerCase();
String a = "a";
for (int i = 0; i<phrase.length(); i++ ) {
char count = phrase.charAt(i);
if (Character.isLetter(count))
countLetter[a.compareTo(phrase.substring(i))*-1] = countLetter[a.compareTo(phrase.substring(i))*-1] + 1;
}
for (int i = 0; i<26; i++) {
if (countLetter[i]>0) {
System.out.println(alphabet[i] + ": " + countLetter[i]);
}
}
我不确定我做错了什么,那么我怎样才能让“a”保持不变?
最佳答案
永远不要依赖 compareTo
的确切返回值,除非它是 0
。如果要将字符 a
、b
、c
等转换为数组的索引,最好的方法是找出它们之间的区别一个一个
。这样 a
被翻译成 0
,b
被翻译成 1
,等等:
for (int i = 0; i < phrase.length(); i++) {
char ch = phrase.charAt(i);
if (Character.isLetter(ch)) {
countLetter[ch - 'a']++;
}
}
关于java - 比较相同的字符给出不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64935054/