需求:机票价格按照淡季旺季、头等舱经济舱收费、输入机票原价、月份和头等舱或经济舱
旺季(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;
}
}