java机票价格代码——利用方法简化

需求:机票价格按照淡季旺季、头等舱经济舱收费、输入机票原价、月份和头等舱或经济舱

旺季(5-10月)头等舱9折,经济舱8.5折

淡季(11-来年4月)头等舱7折,经济舱6.5折

原代码:

public class test1 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入机票原价:");
        double price = sc.nextInt();
        System.out.println("请输入当前月份:");
        int month = sc.nextInt();
        System.out.println("请输入选择头等舱1还是经济舱2:");
        int sit = sc.nextInt();

        // 有效月份
        if (month >= 1 && month <= 12) {
            // 旺季
            if (month >= 5 && month <= 10) {
                // 头等舱
                if (sit == 1) {
                    price = price * 0.9;
                // 经济舱
                } else if (sit == 2) {
                    price = price * 0.85;
                } else {
                    System.out.println("没有这个舱位");
                }
               // 淡季
            } else {
                // 头等舱
                if (sit == 1) {
                    price = price * 0.7;
                // 经济舱
                } else {
                    price = price * 0.65;
                }
            }
            System.out.println("现在机票的价格为:" + price);
        } else {
            System.out.println("请输入有效月份");
        }
    }
}

其中中间选舱位代码重复,抽取成方法以优化代码

public class test1 {
    public static void main(String[] args) {
        //键盘录入
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入机票原价:");
        double price = sc.nextInt();
        System.out.println("请输入当前月份:");
        int month = sc.nextInt();
        System.out.println("请输入选择头等舱1还是经济舱2:");
        int num = sc.nextInt();

        // 有效月份
        if (month >= 1 && month <= 12) {
            // 旺季
            if (month >= 5 && month <= 10) {
                sit(price,num,0.9,0.85);
               // 淡季
            } else {
                sit(price,num,0.7,0.65);
            }
            System.out.println("现在机票的价格为:" + price);
        } else {
            System.out.println("请输入有效月份");
        }

    }
    // 定义一个方法
    // 需要传入原价、舱位、不同舱位的折扣
    public static double sit(double price, int num, double v1, double v2){
        // 头等舱
        if (num == 1) {
            price = price * v1;
        // 经济舱
        } else if (num == 2) {
            price = price * v2;
        } else {
            System.out.println("没有这个舱位");
        }
        return price;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值