java中的for循环

来源:百度知道 编辑:UC知道 时间:2024/05/31 02:52:58
请看下面的这个程序,我想输出的是:
accdfsss
a 1
c 2
d 1
f 1
s 3
但是输出的为什么是:
accdfsss
a 1
c 2
c 2
d 1
f 1
s 3
s 3
s 3
请各位帮忙啊?
package net.nd27.chapter6;

import java.util.Scanner;

public class Demo16 {

public static void main(String args[]) {
// Scanner sc = new Scanner(System.in);
// String s = sc.next();
String s="acssfcds";
char ch[] = s.toLowerCase().toCharArray();

for (int i = 0; i < ch.length - 1; i++) {
for (int j = 0; j < ch.length - 1 - i; j++) {
if (ch[j] > ch[j + 1]) {
char temp = ch[j];
ch[j] = ch[j + 1];
ch[j + 1] = temp;
}
}
}

for (int i = 0; i < ch.length; i++) {
System.out.print(ch[i]);

}
System.out.println();

int[] count = new int[ch.length];
char t1 = 0;
char t2 = 0;

你写的太复杂了,看我的

public static void main(String[] args)
{
int[] dic=new int[255];
String s = "acssfcds";
for(int i=0;i<s.length();i++)
dic[(int)(s.charAt(i))]++;
for(int j=0;j<255;j++)
if(dic[j]>0)
System.out.println((char)j+" "+dic[j]);
}

因为你没有处理重复的字母

在输出的是很判断下重复字母就可以了