Java 程序实现地铁路线查询,判断车站是否存在并计算费用和时间
import java.util.Scanner;
public class Train { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String[] stations = {"西流湖", "南京南站", "南京站", "鼓楼站", "新街口站", "明发广场站", "小市站", "安德门站", "天隆寺站", "软件大道站", "花神庙站", "南京南站"};
// 输入上车站
System.out.println('请输入上车站:');
String startStation = sc.nextLine();
while (!isStationExist(stations, startStation)) {
System.out.println('您输入的上车站:' + startStation + '不存在,请重新输入上车站:');
startStation = sc.nextLine();
}
// 输入到达站
System.out.println('请输入到达站:');
String endStation = sc.nextLine();
while (!isStationExist(stations, endStation)) {
System.out.println('您输入的到达站:' + endStation + '不存在,请重新输入到达站:');
endStation = sc.nextLine();
}
// 计算站数和费用
int startIndex = getIndex(stations, startStation);
int endIndex = getIndex(stations, endStation);
int count = Math.abs(endIndex - startIndex);
int fee = count * 1;
System.out.println('从' + startStation + '到' + endStation + '经过' + count + '站收费' + fee + '元,大约需要' + (count * 2) + '分钟');
}
/**
* 判断站名是否存在
*
* @param stations 所有站名
* @param station 待判断的站名
* @return true:存在,false:不存在
*/
private static boolean isStationExist(String[] stations, String station) {
for (String s : stations) {
if (s.equals(station)) {
return true;
}
}
return false;
}
/**
* 获取站名在数组中的下标
*
* @param stations 所有站名
* @param station 待获取下标的站名
* @return 站名在数组中的下标
*/
private static int getIndex(String[] stations, String station) {
for (int i = 0; i < stations.length; i++) {
if (stations[i].equals(station)) {
return i;
}
}
return -1;
}
}
原文地址: https://www.cveoy.top/t/topic/n7xI 著作权归作者所有。请勿转载和采集!