这个是练习构造方法的,因为机票打折的过程的实现的代码是有些重复的,所以我就想着,构造成方法来实现。
题目的要求是:
机票价格按照淡季和旺季,头等舱和经济舱收费,从键盘输入机票的原价和月份,以及是头等舱还是经济舱的信息。
旺季(5-10月)头等舱打九折,经济舱8.5折,淡季(11月-来年4月)头等舱7折,经济舱6.5折。
我第一次的时候不定义方法来实现的,写得有些乱,而且重复很多。
import java.util.Scanner;
public class Mailfeijipiao {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("请输入票价:");
double price=sc.nextInt();
System.out.println("请输入月份:");
int time=sc.nextInt();
System.out.println("请输入座位等级(1为头等舱,2为经济舱):");
int dengji= sc.nextInt();
if(5<=time&&time<=10){
if (dengji==1){
double finalprice=0.9*price;
System.out.println("最终的价格为"+finalprice);
}
else {
double finalprice=0.85*price;
System.out.println("最终的价格为"+finalprice);
}
}
else if(4<=time&&time<=11){
if (dengji==1){
double finalprice=0.7*price;
System.out.println("最终的价格为"+finalprice);
}
else {
double finalprice=0.65*price;
System.out.println("最终的价格为"+finalprice);
}
}
else {
System.out.println("输入的月份有误");
}
}
}
然后,下面这里是我尝试定义了一个方法来的。
import java.util.Scanner;
public class Maijipiao_plus {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入票价:");
int a = sc.nextInt();
System.out.println("请输入月份:");
int b = sc.nextInt();
System.out.println("请输入票价等级(1为头等舱,2为经济舱):");
int c = sc.nextInt();
Dazhe(a, b, c);
}
public static void Dazhe(int price, int month, int dengji) {
if (5 <= month && month <= 10) {
if (dengji == 1) {
int finalprice = (int) (price * 0.9);
System.out.println("最终的价格是" + finalprice);
} else {
int finalprice = (int) (price * 0.85);
System.out.println("最终的价格是" + finalprice);
}
} else if (4 <= month && month <= 11) {
if (dengji == 1) {
int finalprice = (int) (price * 0.7);
System.out.println("最终的价格是" + finalprice);
} else {
int finalprice = (int) (price * 0.65);
System.out.println("最终的价格是" + finalprice);
}
} else {
System.out.println("输入的月份或等级有误");
}
}
}