求一个java小程序,查出一个字符串中出现次数最多的,并输出此字符
2个回答
展开全部
把原理基本写了一下,没有考虑什么设计,不过可以运行,你改进一下吧
package test;
import java.util.*;
import java.lang.*;
import java.lang.reflect.*;
class charCount implements Comparable {
public int count=0;
public String charN = null;
public int compareTo(Object o) {
if(o instanceof charCount) {
charCount charN2 = (charCount)o;
return charN2.count - this.count;
}
return -1;
}
}
public class testclass {
public static void main(String[] args) {
HashMap hm = new HashMap();
String aaa = "adfkljcxvvcsahasidfnn";
for(int i=0; i<aaa.length(); i++) {
String charN = String.valueOf(aaa.charAt(i));
if(hm.containsKey(charN)) {
charCount charC = (charCount)hm.get(charN);
charC.count = charC.count + 1;
} else {
charCount charC = new charCount();
charC.charN = charN;
charC.count = 1;
hm.put(charN, charC);
}
}
Object[] c = hm.values().toArray();
Arrays.sort(c);
System.out.print(((charCount)c[0]).charN+":"+((charCount)c[0]).count);
}
}
package test;
import java.util.*;
import java.lang.*;
import java.lang.reflect.*;
class charCount implements Comparable {
public int count=0;
public String charN = null;
public int compareTo(Object o) {
if(o instanceof charCount) {
charCount charN2 = (charCount)o;
return charN2.count - this.count;
}
return -1;
}
}
public class testclass {
public static void main(String[] args) {
HashMap hm = new HashMap();
String aaa = "adfkljcxvvcsahasidfnn";
for(int i=0; i<aaa.length(); i++) {
String charN = String.valueOf(aaa.charAt(i));
if(hm.containsKey(charN)) {
charCount charC = (charCount)hm.get(charN);
charC.count = charC.count + 1;
} else {
charCount charC = new charCount();
charC.charN = charN;
charC.count = 1;
hm.put(charN, charC);
}
}
Object[] c = hm.values().toArray();
Arrays.sort(c);
System.out.print(((charCount)c[0]).charN+":"+((charCount)c[0]).count);
}
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询