編程題目:
8.(Map)利用Map,完成下面的功能:
在控制檯(console)讀入一個字符串,表示一個年份,輸出該年的世界盃冠軍是哪 ##支球隊。如果該年沒有舉辦世界盃,則輸出:沒有舉辦世界盃。
示例代碼:
國家類:
package program.collection.exercise08;
/**
* 國家類
*/
public class Country{
private int number;
private String year;
private String country;
public Country(){}
public Country(int number, String year, String country) {
super();
this.number = number;
this.year = year;
this.country = country;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
package program.collection.exercise08;
import java.util.*;
/**
* 8.(Map)利用Map,完成下面的功能:
* 在控制檯(console)讀入一個字符串,表示一個年份,輸出該年的世界盃冠軍是哪支球隊。
* 如果該年沒有舉辦世界盃,則輸出:沒有舉辦世界盃。
* 附:世界盃冠軍以及對應的奪冠年份,請參考本章附錄。
* 屆數 年份 冠軍
* 1,"1930","烏拉圭"
* 2,"1934","意大利"
* 3,"1938","意大利"
* 4,"1950","烏拉圭"
* 5,"1954","德國"
* 6,"1958","巴西"
* 7,"1962","巴西"
* 8,"1966","英格蘭"
* 9,"1970","巴西"
* 10,"1974","德國"
* 11,"1978","阿根廷"
* 12,"1982","意大利"
* 13,"1986","阿根廷"
* 14,"1990","德國"
* 15,"1994","巴西"
* 16,"1998","法國"
* 17,"2002","巴西"
* 18,"2006","意大利"
*/
public class WorldCupMap {
public static void main(String[]args){
System.out.println("請輸入一個年份:");
@SuppressWarnings("resource")
Scanner scanner = new Scanner(System.in);
String time = scanner.next();
//判斷輸入年份
judgeYear(time);
}
//判斷輸入年份
private static void judgeYear(String time) {
Map<Integer,Country> map = new HashMap<Integer,Country>();
map.put(1, new Country(1,"1930","烏拉圭"));
map.put(2, new Country(2,"1934","意大利"));
map.put(3, new Country(3,"1938","意大利"));
map.put(4, new Country(4,"1950","烏拉圭"));
map.put(5, new Country(5,"1954","德國"));
map.put(6, new Country(6,"1958","巴西"));
map.put(7, new Country(7,"1962","巴西"));
map.put(8, new Country(8,"1966","英格蘭"));
map.put(9, new Country(9,"1970","巴西"));
map.put(10, new Country(10,"1974","德國"));
map.put(11, new Country(11,"1978","阿根廷"));
map.put(12, new Country(12,"1982","意大利"));
map.put(13, new Country(13,"1986","阿根廷"));
map.put(14, new Country(14,"1990","德國"));
map.put(15, new Country(15,"1994","巴西"));
map.put(16, new Country(16,"1998","法國"));
map.put(17, new Country(17,"2002","巴西"));
map.put(18, new Country(18,"2006","意大利"));
boolean exit = false; //定義輸入年份是否舉辦世界盃
Iterator<Integer> iterator = map.keySet().iterator();
while(iterator.hasNext()){
Integer key = iterator.next();
Country country = map.get(key);
//若存在輸入年份,則輸出該年份世界盃冠軍
if(time.equals(country.getYear())){
System.out.println(country.getYear()+"年世界盃冠軍是:"+country.getCountry());
exit = true;
}
}
//若不存在輸入年份,則輸出該年份沒有舉辦世界盃
if(exit == false){
System.out.println(time+"年沒有舉辦世界盃!");
}
}
}