35.综合练习:买飞机票

//机票价格按照淡季旺季,头等舱经济舱收费
//键盘录入机票原价、月份和仓位
//旺季(5月到10月):头等舱9折,经济舱8.5折
//淡季(11月到下一年的4月):头等舱7折,经济舱6.5折
import java.util.Scanner;

public class 飞机票 {
 
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入机票原价:");
        int price = sc.nextInt();
        System.out.println("请输入月份:");
        int month = sc.nextInt();
        System.out.println("请输入仓位(1-头等舱  2-经济舱):");
        int seat = sc.nextInt();
        if (month >= 5 && month <= 10) {
            if (seat==1){
                price=(int)(price*0.9);
            }
            else if (seat==2){
                price=(int)(price*0.85);
            }
            else{
                System.out.println("请正确输入仓位所代表的数字!");
            }
        }else if ((month>=1&&month<=4)||(month>=11&&month<=12)){
            if (seat==1){
                price=(int)(price*0.7);
            }
            else if (seat==2){
                price=(int)(price*0.65);
            }
            else{
                System.out.println("请正确输入仓位所代表的数字!");
            }
        }
        else{
            System.out.println("请正确输入月份!");
        }
        System.out.println("最终票价为:"+price);
    }
}

由于if-else判断语句重复较多,所以采用定义方法来优化代码

优化后代码如下:

import java.util.Scanner;

public class 飞机票 {
   
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入机票原价:");
        int price = sc.nextInt();
        System.out.println("请输入月份:");
        int month = sc.nextInt();
        System.out.println("请输入仓位(1-头等舱  2-经济舱):");
        int seat = sc.nextInt();
        if (month >= 5 && month <= 10) {
            price = getPrice(price, seat, 0.9, 0.85);
        } else if ((month >= 1 && month <= 4) || (month >= 11 && month <= 12)) {
            price = getPrice(price, seat, 0.7, 0.65);
        } else {
            System.out.println("请正确输入月份!");
        }
        System.out.println("最终票价为:" + price);
    }

    public static int getPrice(int price, int seat, double a, double b) {
        if (seat == 1) {
            price = (int) (price * a);
        } else if (seat == 2) {
            price = (int) (price * b);
        } else {
            System.out.println("请正确输入仓位所代表的数字!");
        }
        return price;
    }
}

相关推荐

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-20 00:40:02       52 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-20 00:40:02       54 阅读
  3. 在Django里面运行非项目文件

    2024-07-20 00:40:02       45 阅读
  4. Python语言-面向对象

    2024-07-20 00:40:02       55 阅读

热门阅读

  1. 基于深度学习的车距检测系统

    2024-07-20 00:40:02       17 阅读
  2. 有些面试,纯属是浪费时间和精力!

    2024-07-20 00:40:02       14 阅读
  3. 手写简易版Spring IOC容器02【学习】

    2024-07-20 00:40:02       13 阅读
  4. 新手教程---python-函数(新添加)

    2024-07-20 00:40:02       20 阅读