项目开始:
昨天的Java学习到了Map集合,有一个公交线路的Demo,在编程过程中出现了一些问题,写篇博客记录一下。这个项目的需求是实现输入上车站和下车站,预估车程耗时并输出车费。
项目分析与实现:
看到需求后,第一考虑就是通过Map来创建集合并将数据添加到集合中。
Map<Integer,String> map=new HashMap<>();
map.put(1 ,"朱辛庄");
map.put(2 ,"育知路");
map.put(3 ,"平西府");
map.put(4 ,"回龙观东大街");
map.put(5 ,"霍营");
map.put(6 ,"育新");
map.put(7 ,"西小口");
map.put(8 ,"永泰庄");
map.put(9 ,"林萃桥");
map.put(10 ,"森林公园南门");
map.put(11 ,"奥林匹克公园");
map.put(12 ,"奥体中心");
map.put(13 ,"北土城");
map.put(14 ,"安华桥");
map.put(15 ,"安德里北街");
map.put(16 ,"鼓楼大街");
map.put(17 ,"什刹海");
map.put(18 ,"南锣鼓巷");
map.put(19 ,"中国美术馆" );
在添加完数据后创建Scanner对象来接收控制台输入并对比集合中的数据,通过get方法获取键(车站编号)。
Scanner sc=new Scanner(System.in);
System.out.println("请输入上车车站");
String aboardStation=sc.nextLine(); //上车车站的录入
System.out.println("请输入下车车站");
String debusStation==sc.nextLine();; //下车车站的录入
int key1=0,key2=0;
for (Map.Entry<Integer, String> entry : entries) {
if (entry.getValue().equals(aboardStation)){
key1=entry.getKey();
}
}
for (Map.Entry<Integer, String> entry1 : entries) {
if (entry1.getValue().equals(debusStation)){
key2=entry1.getKey();
}
}
原本是这样做的,但是在编写的时候就发现了一些逻辑上的问题。第一在上车车站的录入后立刻录入下车车站就实现不了题目例示效果(先判断上车车站的合法性再接收下车车站),且无标志位来判断上车车站是否存在。于是做出以下修改。
Scanner sc=new Scanner(System.in);
System.out.println("请输入上车车站");
String aboardStation=sc.nextLine();
String debusStation=null;
int key1=0,key2=0;
int flag1=0,flag2=0;
Set<Map.Entry<Integer, String>> entries = map.entrySet();
for (Map.Entry<Integer, String> entry : entries) {
if (entry.getValue().equals(aboardStation)){
key1=entry.getKey();
flag1=1;
System.out.println("请输入下车车站");
debusStation=sc.nextLine();
for (Map.Entry<Integer, String> entry1 : entries) {
if (entry1.getValue().equals(debusStation)){
key2=entry1.getKey();
flag2=1;
break;
}
}
break ;
}
}
修改后,嵌套的for循环就可以实现在上车车站录入正确之后再进行下车车站的录入和验证合法性,且添加标志位实现了参数存在性的验证,用for循环的break也少量的提高了代码的运行效率。
最后就是一些简单的判断和输出语句。
if (flag1==0) System.out.println("您输入的上车车站不存在!");
if (flag1==1&&flag2==0) System.out.println("您输入的下车车站不存在!");
if (flag1==1&&flag2==1){
int stationNum=key2-key1;
System.out.println("您坐了"+stationNum+"站"+"大约需要"+stationNum*2+"分钟!");
int money=(stationNum-5)*2+4;
if (stationNum<4&&stationNum>0) System.out.println("您从"+aboardStation+"到"+debusStation+"一共收费三元,感谢您的乘坐!");
else if (stationNum>3&&stationNum<6) System.out.println("您从"+aboardStation+"到"+debusStation+"一共收费4元,感谢您的乘坐!");
else if (stationNum>5&&stationNum<11) System.out.println("您从"+aboardStation+"到"+debusStation+"一共收费"+money+"元,感谢您的乘坐!");
else System.out.println("您从"+aboardStation+"到"+debusStation+"一共收费14元,感谢您的乘坐!");
System.out.println("-----------------------------");
}
}
}
总结:
这个案例非常简单,也没有复杂的算法和逻辑,需要的就是思维的严密性,后期做题还是得考虑周全。