1.廣州地鐵二號線站編號和站名對應關係如下:
1=廣州南站、2=石壁、3=會江、4=南浦、5=洛溪、6=南洲、7=東曉南、8=江泰路、9=昌崗、10=江南西、11=市二宮、12=海珠廣場、13=公園前、14=紀念堂、15=越秀公園、16=廣州火車站、17=三元里、18=飛翔公園、19=白雲公園、20=白雲文化廣場、
21=蕭崗、22=江夏、23=黃邊、24=嘉禾望崗
將以上對應關係的數據存儲到map集合中,key:表示站編號,value:表示站名,並遍歷打印
2.計算地鐵票價規則:
總行程3站內(包含3站)收費2元,
3站以上但不超過6站(包含6站)的收費4元,
6站以上的,在4元的基礎上,每多2站增加1元,不夠2站的也按2站算,
10元封頂;
3.打印格式(需要對鍵盤錄入的上車站和到達站進行判斷,如果沒有該站,提示重新輸入,
直到站名存在爲止):注意:每站需要2分鐘
請輸入上車站:
沙河
您輸入的上車站:【沙河】不存在,請重新輸入上車站:
上地
您輸入的上車站:【上地】不存在,請重新輸入上車站:
廣州南站
請輸入到達站:
沙河
您輸入的到達站:【沙河】不存在,請重新輸入到達站:
西二旗
您輸入的到達站:【西二旗】不存在,請重新輸入到達站:
海珠廣場
從【廣州南站】到【海珠廣場】共經過11站收費9元,大約需要22分鐘
public class Station {
private Map<Integer,String> map = new HashMap<Integer, String>();
/**
* 初始化map站點數據
*/
public void initMap(){
String s = "1=廣州南站、2=石壁、3=會江、4=南浦、5=洛溪、6=南洲、7=東曉南、8=江泰路、9=昌崗、10=江南西、11=市二宮、12=海珠廣場、13=公園前、14=紀念堂、15=越秀公園、16=廣州火車站、17=三元里、18=飛翔公園、19=白雲公園、20=白雲文化廣場、21=蕭崗、22=江夏、23=黃邊、24=嘉禾望崗";
//把站點信息存入到map對象中
String[] array = s.split("、");
for(String str:array) {
String[] array2 = str.split("=");
map.put(Integer.parseInt(array2[0]), array2[1]);
}
}
/**
* 遍歷map所有元素
*/
public void showMap() {
//遍歷map所有元素
for(Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();it.hasNext();) {
Map.Entry<Integer, String> e = it.next();
System.out.println("第"+e.getKey()+"站:"+e.getValue());
}
}
/**
* 獲取所有站點信息
* @return
*/
public Collection<String> getStations(){
//獲取所有的站點
return map.values();
}
/**
* 根據站點名稱獲取站點編號
* @param name 站點名稱
* @return
*/
public int getNoByName(String name) {
for(Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();it.hasNext();) {
Map.Entry<Integer, String> e = it.next();
if(e.getValue().equals(name)) {
return e.getKey();
}
}
return 0;
}
/**
* 根據站點編號計算票價
* @param upNo 上車站編號
* @param downNo 到達站編號
* @return
*/
public int getPrice(int upNo,int downNo) {
int cha = Math.abs(downNo-upNo);//求絕對值
int price = 0;
if(cha<=3) {
price = 2;
}else if(cha<=6) {
price = 4;
}else if(cha<=16) {
int a = (cha-6)/2;
if((cha-6)%2!=0) {
a++;
}
price = 4 + a;
}else {
price = 10;
}
return price;
}
}
public class Test2 {
public static void main(String[] args) {
Station s = new Station();
s.initMap();
s.showMap();
Scanner sc = new Scanner(System.in);
System.out.println("請輸入上車站:");
//獲取所有的站點
Collection<String> list = s.getStations();
//上車站名稱
String up = null;
//到達站名稱
String down = null;
while(true) {
up = sc.next();
if(list.contains(up)) {
break;
}
System.out.println("您輸入的上車站:【"+up+"】不存在,請重新輸入上車站:");
}
System.out.println("請輸入到達站:");
while(true) {
down = sc.next();
if(list.contains(down)) {
break;
}
System.out.println("您輸入的到達站:【"+down+"】不存在,請重新輸入到達站:");
}
int upNo = s.getNoByName(up);
int downNo = s.getNoByName(down);
int cha = downNo-upNo;
int price = s.getPrice(upNo, downNo);
System.out.println("從【"+up+"】到【"+down+"】共經過"+cha+"站收費"+price+"元,大約需要 "+(cha*2)+"分鐘");
}
}