不使用数组的java字符串中的最大字符数请

不使用数组的java字符串中的最大字符数请,java,Java,我需要在java中查找字符串中字符的最大出现次数,但是如果有多个字符具有多个出现次数。它将打印第一个字符。例如,如果我尝试aabbb,它将打印a:2而不是b:3。我不知道如何使用数组。请给我一些建议 int count = 1; int max = 1; String newstring = ""; String currentletter = ""; String finalletter = ""; for (int i = 0; i <

我需要在java中查找字符串中字符的最大出现次数,但是如果有多个字符具有多个出现次数。它将打印第一个字符。例如,如果我尝试aabbb,它将打印a:2而不是b:3。我不知道如何使用数组。请给我一些建议

    int count = 1;
    int max = 1;
    String newstring = "";
    String currentletter = "";
    String finalletter = "";
    for (int i = 0; i < word.length() - 1; i++) {
        currentletter = word.substring(i, i+1);
        if (newstring.contains(currentletter)) {
            currentletter = "";
        } else {
            newstring += currentletter;
            for (int j = i+1; j < word.length(); j++) {
                if (currentletter.equals(word.substring(j, j+1))) {
                    count++;
                    finalletter = currentletter;
                }
            }
            if (count > max) {
                max = count;
                count = 0;
                currentletter = "";
                System.out.print(finalletter + ": ");
            }
        }
    }
    System.out.println(max + " ");
}
int count=1;
int max=1;
字符串newstring=“”;
字符串currentletter=“”;
字符串finalletter=“”;
for(int i=0;i最大值){
最大值=计数;
计数=0;
currentletter=“”;
系统输出打印(finalletter+“:”);
}
}
}
System.out.println(最大+“”);
}
我将使用a和两个循环。首先,通过迭代
字符串
并计算字母的出现次数来填充
映射
。其次,迭代
映射的条目集
,并将其与局部最大值进行比较。最后,显示结果(或指示无结果的消息)。像


不使用数组?猜猜
字符串的后面是什么;)只是确认一下:对于
aabbb
来说,正确的结果应该是
b:3
(这就是我对“最大出现次数”的解释),但它实际上给出了错误的
a:2
?是的。结果应该是b:3,但我的代码给了我a:2。谢谢。我还没学会地图。有没有更简单的方法?我的原始代码有什么问题吗?谢谢。@IanDong我的原始代码有什么问题吗。看起来您需要进行一些调试。以下是一些帮助您开始的方法。
String s = "aabbb";
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
    char ch = s.charAt(i);
    map.put(ch, 1 + map.getOrDefault(ch, 0));
}
Map.Entry<Character, Integer> max = null;
for (Map.Entry<Character, Integer> entry : map.entrySet()) {
    if (max == null || max.getValue() < entry.getValue()) {
        max = entry;
    }
}
if (max != null) {
    System.out.printf("%c: %d%n", max.getKey(), max.getValue());
} else {
    System.out.println("no result");
}
b: 3