黑马程序员技术交流社区
标题:
看看这个程序哪出问题了
[打印本页]
作者:
linuxpara910829
时间:
2015-2-14 17:03
标题:
看看这个程序哪出问题了
public class Test1{
public static void main(String [] args){
String str = "abcdekka27qoq";
Map<Character, Integer> map = new TreeMap<Character, Integer>();
map = strToMap(map,str);
printMap(map);
}
public static Map<Character, Integer> strToMap(Map<Character, Integer> map,String str){
char [] chs = str.toCharArray();
for(int index=0;index<chs.length;index++){
if(!(map.containsKey(chs[index]))){
map.put(chs[index],1);
}
else{
int value = map.get(chs[index]);
map.put(chs[index],++value);
}
}
return map;
}
public static void printMap(Map<Character,Integer> map){
Set<Map.Entry<Character,Integer>> set = map.entrySet();
Iterator<Map.Entry<Character,Integer>> it = set.iterator();
while(it.hasNext()){
char key = it.next().getKey();
int value = it.next().getValue();
System.out.println(key+"("+value+")");
}
}
}
作者:
linuxpara910829
时间:
2015-2-14 17:32
问题解决了 我用keyset取出就没问题 为什么我用entryset取出的时候会丢东西呢?
作者:
汝建国
时间:
2015-2-14 17:44
一点注释也没有啊这时
作者:
关山明月
时间:
2015-2-14 20:56
strToMap() 方法得到想要的结果了,但是打印出来的却不是自己得到的结果,问题在这里:
while(it.hasNext()){
char key = it.next().getKey();
int value = it.next().getValue();
System.out.println(key+"("+value+")");
}
复制代码
char key=it.next().getKey(); 如果是取出map集合中的第一个键的话,如a ,那下一句:int value=it.next().getValue(); 取出的则是下一个键映射的value值了。。。,如 b 的value.
while(it.hasNext()){
Map.Entry<Character,Integer> me=it.next();
char key = me.getKey();
int value = me.getValue();
System.out.println(key+"("+value+")");
}
复制代码
这样就可以得到结果了
作者:
linuxpara910829
时间:
2015-2-14 22:58
嗯 谢谢你 太对了 , 我为了省事,没那么写结果出了问题自己也查不出来
作者:
艺多不压身丶
时间:
2015-2-14 22:59
我给你从写了一个。
package pack;
import java.util.*;
class MaoTest3{
public static void main(String[] args){
charCount("abcdekka27qoq");
}
public static String charCount(String s){
char[] chs=s.toCharArray();
TreeMap<Character,Integer>tm=new TreeMap<Character,Integer>();
int count=0;
for(int x=0; x<chs.length; x++){
if(!(chs[x]>='a'&&chs[x]<='z'||chs[x]>='A'&&chs[x]<='Z'))
continue;
Integer value=tm.get(chs[x]);
if(value!=null)
count=value;
count++;
tm.put(chs[x],count);
count=0;
}
System.out.println(tm);
StringBuilder sb=new StringBuilder();
Set<Map.Entry<Character,Integer>>entry=tm.entrySet();
Iterator<Map.Entry<Character,Integer>>it=entry.iterator();
while(it.hasNext()){
Map.Entry<Character,Integer>me=it.next();
Character key=me.getKey();
Integer value=me.getValue();
sb.append(key+"("+value+")");
}
return sb.toString();
}
}
复制代码
作者:
你的微笑很美
时间:
2015-2-14 23:13
好复杂啊
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2