java排序的问题请教大神

dzbkq_110 2016-07-17 04:47:38
package _0717;

import java.util.Arrays;
import java.util.Scanner;
/**从键盘接收字符串,找出字符串中共有多少种字符,每种有多少个。我先转为数组,然后sort排序,循环第i和i+1比较,
* 只需要比length-1次,但是我的代码写的有问题,无法得到最后一批。如果按我的思路能不能sort完之后在数组的最后加一个null
* 这样我比到length-1,最后一个数肯定不是null,循环进入else就可以打印出最后一批了。问题是代码怎么写
*/
public class Listall {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String string=sc.next();
//字符转为数组,排序
char[] chars=string.toCharArray();
Arrays.sort(chars);
System.out.println(chars);
//找出相同的元素和每个元素的个数
int sum=1;int sorts=1;
for(int i=0;i<(chars.length-1);i++){
if(chars[i]==(chars[i+1])){
sum+=1;
}
else{
sorts+=1;
String s=chars[i]+"有"+sum+"个";
System.out.println(s);
sum=1;
}
}
}
}
...全文
126 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
dzbkq_110 2016-07-17
  • 打赏
  • 举报
回复
谢谢,我试了。连按两次回车程序才有用,两次回车之间不输入字符。按第一次回车换行后,还能继续输入,再按回车输出的数据就不准了
rickylin86 2016-07-17
  • 打赏
  • 举报
回复

import java.util.Scanner;


public class Test{
	public static void main(String[] args){
		System.out.print("Input the content:");
		Scanner keyboard = new Scanner(System.in);
		String content = keyboard.nextLine();
		String first = null;
		int count = 0;
		while(content.length() != 0){
			first = content.charAt(0) + "";
			count = content.length() - (content = content.replaceAll("[" + first + "]","")).length();
			System.out.printf("'%s' 出现 %d 次.\n",first,count);
		}
	}
}

62,628

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧