案例:
卖飞机票
需求:
机票价格按照淡季旺季、头等舱和经济舱收费、输入机票原价、月份和头等舱或经济舱。按照如下规则计算机票价格:旺季(5 - 10 月)头等舱 9 折,经济舱 8.5 折,淡季(11 月到来年 4 月)头等舱 7 折,经济舱 6.5 折。
代码一:
//卖飞机票:
//代码一:
package demo01;
import java.util.Scanner;
public class HelloJava {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入机票原价:");
double ticketPrices = sc.nextInt();
System.out.println("请输入购买机票的月份:");
int month = sc.nextInt();
System.out.println("舱位是头等舱还是经济舱?(头等舱用0表示,经济舱用1表示!)");
int shippingSpace = sc.nextInt();
sc.close();
//旺季:
if(month >= 5 && month <= 10){
//旺季头等舱:
if(shippingSpace == 0){
ticketPrices *= 0.9;
//旺季经济舱:
}else if(shippingSpace == 1){
ticketPrices *= 0.85;
//输入的舱位错误:
}else{
System.out.println("输入的舱位不合法!");
}
//淡季:
}else if((month >= 1 && month <= 4) || (month >= 11 && month <= 12)){
//淡季头等舱:
if(shippingSpace == 0){
ticketPrices *= 0.7;
//淡季经济舱:
}else if(shippingSpace == 1){
ticketPrices *= 0.65;
//输入的舱位错误:
}else{
System.out.println("输入的舱位不合法!");
}
//输入的月份错误:
}else{
System.out.println("输入的月份不合法!");
}
System.out.println("机票的价格为:" + ticketPrices + "元!");
}
}
运行结果一:
代码二:
//卖飞机票:
//代码二:
package demo01;
import java.util.Scanner;
public class HelloJava {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入机票原价:");
double ticketPrices = sc.nextInt();
System.out.println("请输入购买机票的月份:");
int month = sc.nextInt();
System.out.println("舱位是头等舱还是经济舱?(头等舱用0表示,经济舱用1表示!)");
int shippingSpace = sc.nextInt();
sc.close();
//旺季:
if(month >= 5 && month <= 10){
//调用方法:
ticketPrices = getPrice(ticketPrices, shippingSpace, 0.9, 0.85);
//淡季:
}else if((month >= 1 && month <= 4) || (month >= 11 && month <= 12)){
//调用方法:
ticketPrices = getPrice(ticketPrices, shippingSpace, 0.7, 0.65);
//输入的月份错误:
}else{
System.out.println("输入的月份不合法!");
}
System.out.println("机票的价格为:" + ticketPrices + "元!");
}
//定义计算头等舱和经济舱价格的方法:
public static double getPrice(double ticketPrices, int shippingSpace, double discount1, double discount2){
//头等舱:
if(shippingSpace == 0){
ticketPrices *= discount1;
//经济舱:
}else if(shippingSpace == 1){
ticketPrices *= discount2;
//输入的舱位错误:
}else{
System.out.println("输入的舱位不合法!");
}
return ticketPrices;
}
}
运行结果二: