//机票价格按照淡季旺季,头等舱经济舱收费 //键盘录入机票原价、月份和仓位 //旺季(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;
}
}