需求:
机票价格按照淡季旺季、头等舱和经济舱收费、输入机票原价、月份和头等舱或经济舱。
按照如下规则计算机票价格:旺季(5-10月)头等舱9折,经济舱8.5折,淡季(11月到来年4月)头等舱7折,经济舱6.5折。
分析:
定义一个方法可以进行键盘录入机票原价、月份和机舱类型。
使用if判断月份是是旺季还是淡季,使用switch分支判断是头等舱还是经济舱。
选择对应的折扣进行计算并返回计算的结果。
package com.itheima.test;
import java.util.Scanner;
/*
Scanner类
public int nextInt() : 录入一个整数
public int next() : 录入一个字符串 , 碰到空格符号结束
public int nextLine() : 录入一个字符串 , 碰到回车键结束
*/
public class Test1 {
public static void main(String[] args) {
// 1 键盘录入数据
Scanner sc = new Scanner(System.in);
System.out.println("请输入机票的价格:");
double price = sc.nextDouble();
System.out.println("请输入当前的月份:");
int month = sc.nextInt();
System.out.println("请输入机舱的类型:");
String type = sc.next();
double result = calc(type, month, price);
System.out.println("当前月份为" + month + "月 , 您定制的是" + type + ", 花费的金额为:" + result);
}
/*
方法的功能 : 接收机舱的类型 , 月份 , 价格 , 返回打折之后的价格
两个明确
1 返回值类型 : double
2 参数列表 : String type , int month , double price
*/
public static double calc(String type, int month, double price) {
if (month >= 5 && month <= 10) {
// 旺季
switch (type) {
case "头等舱":
return price * 0.9;
case "经济舱":
return price * 0.85;
default:
System.out.println("录入的仓位有误!");
break;
}
} else if (month == 11 || month == 12 || (month >= 1 && month <= 4)) {
// 淡季
switch (type) {
case "头等舱":
return price * 0.7;
case "经济舱":
return price * 0.65;
default:
System.out.println("录入的仓位有误!");
break;
}
} else {
System.out.println("录入的月份有误!");
}
// 如果类型或者月份存在问题 , 那么直接返回-1
return -1;
}
public static void method() {
Scanner sc = new Scanner(System.in);
System.out.println("录入一个整数:");
int num = sc.nextInt();// 45678 回车
System.out.println("num:" + num);
// // public int next() : 录入一个字符串
// System.out.println("录入一个字符串");
// String s = sc.next();
// System.out.println("s:" + s);
// public int nextLine() : 录入一个字符串
sc.nextLine();// 抵消的是回车字符
System.out.println("录入一个字符串");
String s = sc.nextLine();
System.out.println("s:" + s);
}
}