我正在进行一项任务,我必须接受一个字符串然后显示字符串中的每个字符。我想出了代码,但它正在重复。因此,例如,如果字符串是“aaabcd”,它将打印:
a freq:3
a freq:3
a freq:3
b freq:1
c freq:1
d freq:1
我的目标是只打印一次。这是我的代码。有人能帮我找到我做错的事吗?
char[] charArray = userSort.toCharArray();
char tempChar;
for (int i = 0; i < charArray.length; i++) {
for (int j = 0; j < charArray.length; j++) {
if (charArray[i] < charArray[j]) {
tempChar = charArray[i];
charArray[i] = charArray[j];
charArray[j] = tempChar;
}
}
}
String sortedString = "";
for (int i = 0; i < charArray.length; i++) {
userSort += charArray[i];
}
System.out.println(sortedString + "\n");
int counter;
sortedString = "";
for (int i = 0; i < charArray.length; i++) {
counter = 0;
for (int j = 0; j < charArray.length; j++) {
if (charArray[i] == charArray[j]) {
counter++;
}
}
if (!sortedString.contains("Char: " + charArray[i])) {
if (sortedString.equals("")) {
sortedString += " " + charArray[i] + " freq: " + counter + "\n";
} else {
sortedString += " " + charArray[i] + " freq: " + counter + "\n";
}
}
}
System.out.println(sortedString);
System.out.println("");
答案 0 :(得分:0)
我建议您使用Map
来计算角色出现的次数。
final Map<Character, Integer> map = new HashMap<>();
char[] charArray = userSort.toCharArray();
for( char c : charArray ){
map.merge(c, 1, ( v1, v2 ) -> v1 == null ? v2 : v1 + v2);
}
map.forEach((character, frequency) -> System.out.println(character + " freq: " + frequency ));
好处是一切都变得非常小巧紧凑
答案 1 :(得分:0)
看看计算结果:
for (int i = 0; i < charArray.length; i++) {
counter = 0;
for (int j = 0; j < charArray.length; j++) {
if (charArray[i] == charArray[j]) {
counter++;
}
}
由于charArray已排序(不是吗?),您可以这样做:
for (int i = 0; i < charArray.length; i++) {
counter = 0;
for (int j = i; j < charArray.length && charArray[j] == charArray[i]; j++) {
counter++;
}
因此跳过相同的字符:
for (int i = 0; i < charArray.length; ) {
counter = 0;
for (int j = i; j < charArray.length && charArray[j] == charArray[i]; j++) {
counter++;
}
...
i += counter;