Problem Description
1.从命令行读入一个队名,输出该队获得冠军是哪一年(以下面五届数据作为基础数据)。如果该队没有获得冠军,则输出:队名+“ lose the championship!”。
2.下面是五届世界杯数据:
届数 举办年份 举办地点 冠军
第一届,1930年,Uruguay,Uruguay;
第三届,1938年,France,Italy;
第五届,1954年,Swiss,West Germany;
第七届,1962年,Chile,Brazil;
第十三届,1986年,Mexico,Argentina;
3.要求(用Map实现,下面的m即是Map对象):下面是后半部分代码,请补充前半部分:
if(m.get(temp).equals(str)){
System.out.println(temp);
}
}
}else{
System.out.println( str+" lose the championship!");
}
}
}
Input Description
Italy
Output Description
1938
题解代码
这个题目有点怪 注意看
if (m.get(temp).equals(str))
str是我们的输入 也就是队伍名字
因为 System.out.println(temp); 所以temp一定是 年份
但是if里面又用了m.get(temp).equals(str) 所以可以得出一定存在两个map容器
并且两个map容器一定是一个正着存 一个反着存
import java.util.HashMap; import java.util.Map; import java.util.Scanner; class Main { public static void main(String[] args) { Map<String, String> map = new HashMap<>(); Map<String, String> m = new HashMap<>(); map.put("Uruguay", "1930"); map.put("Italy", "1938"); map.put("West Germany", "1954"); map.put("Brazil", "1962"); map.put("Argentina", "1986"); m.put("1930","Uruguay"); m.put("1938","Italy"); m.put("1954","West Germany"); m.put("1962","Brazil"); m.put("1986","Argentina"); Scanner scanner = new Scanner(System.in); String str = scanner.nextLine(); //输入队名str //temp----获奖年份 if (map.containsKey(str)) { //判断map中有没有该队伍 String temp = map.get(str); //获得队伍获奖年份 if(temp != null) { if (m.get(temp).equals(str)) { System.out.println(temp); } } } else { System.out.println(str + " lose the championship!"); } } }