Java通过键盘输入一个字符串,判断字符串中出现最多的字符并输出该字符和输出出现次数...


package com.string.to;

import java.util.Arrays;
import java.util.Scanner;

public class JudeCount {
public static void main(String[] args) {
System.out.println("请输入你要判断的字符串:");
Scanner s = new Scanner(System.in);
String str = s.nextLine();
char[] ch = str.toCharArray();
Arrays.sort(ch); // 对数组排序
char max = 'a'; // 记录出现次数最多元素
int maxcount = 0; // 记录最大出现次数
int count = 1; // 中间传值参数 判断当前元素出现次数
for (int i = 0; i < ch.length - 1; i++) { // 进行判断
if (ch[i] == ch[i + 1]) {
count++;
}
if (ch[i] != ch[i + 1]) {
if (count > maxcount) {
maxcount = count;
max = ch[i];
}
count = 1;
}
}
System.out.println("出现最多的元素是:" + max + " 次数为:" + maxcount);
}
}





http://jythoner.iteye.com/blog/326625

    推荐阅读