import java.util.HashMap; import java.util.Map; import java.util.Scanner;

public class TrainStation { public static void main(String[] args) { Map<String, Integer> stationMap = new HashMap<String, Integer>(); stationMap.put("机场站", 1); stationMap.put("西流湖", 2); stationMap.put("青山湖", 3); stationMap.put("红谷滩", 4); stationMap.put("卧龙山", 5); stationMap.put("医学院", 6);

    Scanner scanner = new Scanner(System.in);

    String startStation;
    do {
        System.out.println("请输入上车站:");
        startStation = scanner.nextLine();
        if (!stationMap.containsKey(startStation)) {
            System.out.println("您输入的上车站:" + startStation + "不存在,请重新输入上车站:");
        }
    } while (!stationMap.containsKey(startStation));

    String endStation;
    do {
        System.out.println("请输入到达站:");
        endStation = scanner.nextLine();
        if (!stationMap.containsKey(endStation)) {
            System.out.println("您输入的到达站:" + endStation + "不存在,请重新输入到达站:");
        }
    } while (!stationMap.containsKey(endStation));

    int startStationIndex = stationMap.get(startStation);
    int endStationIndex = stationMap.get(endStation);
    int stationCount = endStationIndex - startStationIndex;
    int fee = stationCount * 1;
    int duration = stationCount * 2;

    System.out.println("从" + startStation + "到" + endStation + "经过" + stationCount + "站收费" + fee + "元,大约需要" + duration + "分钟");
}
用 java中Mop集合做对键盘录入的上车站和到达站进行判断如果没有该站提示重新输入直到站名存在为止 在控制台输出: 请输入上车站: 机场站 您输入的上车站:机场站不存在请重新输入上车站: 西流湖

原文地址: https://www.cveoy.top/t/topic/ffnW 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录