需求:
1.机票价格按照淡季旺季、头等舱和经济舱收费、输入机票原价、月份和头等舱或经济舱。
2.机票最终优惠价格的计算方案如下:旺季(5-10月)头等舱9折,经济舱8.5折,淡季(11月到来年4月)头等舱7折,经济舱6.5折。
计算机票优惠价格
import java.util.Scanner;// 定义舱位类型枚举
enum CabinClass {FIRST_CLASS,ECONOMY_CLASS
}// 定义价格计算策略接口
interface PricingStrategy {double calculatePrice(double basePrice);
}// 实现具体的价格计算策略
class PeakSeasonFirstClassPricing implements PricingStrategy {@Overridepublic double calculatePrice(double basePrice) {return basePrice * 0.9;}
}class PeakSeasonEconomyPricing implements PricingStrategy {@Overridepublic double calculatePrice(double basePrice) {return basePrice * 0.85;}
}class OffPeakSeasonFirstClassPricing implements PricingStrategy {@Overridepublic double calculatePrice(double basePrice) {return basePrice * 0.7;}
}class OffPeakSeasonEconomyPricing implements PricingStrategy {@Overridepublic double calculatePrice(double basePrice) {return basePrice * 0.65;}
}// 上下文类,用于设置和切换不同的策略
class PriceCalculator {private PricingStrategy strategy;public PriceCalculator(PricingStrategy strategy) {this.strategy = strategy;}public void setStrategy(PricingStrategy strategy) {this.strategy = strategy;}public double calculateFinalPrice(double basePrice) {return strategy.calculatePrice(basePrice);}
}public class Main {public static void main(String[] args) {// 输入Scanner scanner = new Scanner(System.in);double basePrice;int month;CabinClass cabinClass;// 获取月份do {System.out.print("请输入月份(1-12): ");while (!scanner.hasNextInt()) {System.out.println("请输入有效的数字!");scanner.next();}month = scanner.nextInt();} while (month < 1 || month > 12);// 获取舱位类型System.out.print("请输入舱位类型(头等舱/经济舱): ");String cabin = scanner.next().toLowerCase();cabinClass = cabin.equals("头等舱") ? CabinClass.FIRST_CLASS : CabinClass.ECONOMY_CLASS;// 获取机票原价System.out.print("请输入机票原价: ");while (!scanner.hasNextDouble()) {System.out.println("请输入有效的数字!");scanner.next();}basePrice = scanner.nextDouble();// 根据条件选择相应的价格计算策略PricingStrategy strategy;if (month >= 5 && month <= 10) {strategy = cabinClass == CabinClass.FIRST_CLASS ? new PeakSeasonFirstClassPricing() : new PeakSeasonEconomyPricing();} else {strategy = cabinClass == CabinClass.FIRST_CLASS ? new OffPeakSeasonFirstClassPricing() : new OffPeakSeasonEconomyPricing();}// 计算最终价格PriceCalculator calculator = new PriceCalculator(strategy);double finalPrice = calculator.calculateFinalPrice(basePrice);System.out.println("最终价格为: " + finalPrice);// 关闭 Scannerscanner.close();}
}