Java集合练习4-4,烦请老师检查和指正~
//定义HashMap的对象并添加数据
Map < Integer, String> champion = new HashMap <Integer, String> ();
System.out.println("Please enter keys and values:");
Scanner console = new Scanner(System.in);
int i = 0;
while(i < 3){
System.out.println("Please enter keys:");
int key = console.nextInt();
System.out.println("Please enter values:");
String value = console.next();
champion.put(key, value);
i++;
}
//使用迭代器的方式遍历
System.out.println("Display all the data by iterator:");
Iterator <String> it = champion.values().iterator();
while(it.hasNext()){
System.out.print(it.next() + " ");
}
//使用EntrySet同时获取key和value
Set <Entry <Integer, String>> entrySet = champion.entrySet();
System.out.println("Display both keys and values:");
for(Entry <Integer,String> entry: entrySet){
System.out.print(entry.getKey() + "-" );
System.out.print(entry.getValue());
}
17
收起
正在回答
1回答
同学你好,题目要求使用迭代器遍历key和value,同学的代码只对value进行了遍历。修改后的代码如下图所示:
祝学习愉快~
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星