案例1:购买飞机票
需求:机票价格按照淡季旺季、头等舱和经济舱收费、输入机票原价、月份和舱位类型,机票最终优惠价格的计算方案如下,旺季(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 money = sc.nextDouble();
System.out.println("请输入您需要查询的月份(1-12):");
int month = sc.nextInt();
System.out.println("请输入您需要查询的机舱类型:");
String type = sc.next();
// 写一个方法
double price = fun(money, month, type);
// 结果输出
System.out.println("折扣后的价格为:" + price);
}
public static double fun (double money,int month,String type) {
// 首先判断飞机票类型,因为type就两个值,写switch循环作为大分支比较好
// 定义默认值
double price = 0;
// 大分支
switch (type) {
// 小分支1
case "头等舱":
// 判断月份范围
if (month >= 5 && month <= 10) {
price = money * 0.9;
} else if ((month >= 1 && month <= 4) || (month >= 11 && month <= 12)){
price = money * 0.85;
}
break;
// 小分支2
case "经济舱":
// 判断月份范围
if (month >= 5 && month <= 10) {
price = money * 0.7;
} else if ((month >= 1 && month <= 4) || (month >= 11 && month <= 12)){
price = money * 0.65;
}
break;
// 其它情况 即无效输入
default:
System.out.println("不是正确的月份或者不是正确的机舱类型!");
}
// 返回结果值price
return price;
}
}
案例2:找素数
public class Test2 {
public static void main(String[] args) {
// 1.定义一个循环,找到101-200之间的全部素数
for (int i = 101; i <= 200 ; i++) {
// i = 101 102 103 ... 199 200
// 信号位:标记
boolean flag = true; // 一开始认为当前数据是素数
// 2.判断当前遍历的这个数据是否是素数 素数含义:“大于1的整数中,只能被1和这个数本身整除的数”。 因此从”int j = 2“ 开始进行遍历
// j < i / 2 判断是否能被整除
for (int j = 2; j < i; j++) {
if (i % j == 0){ // 说明不是素数
flag = false;
break;
}
}
// 3.根据判定的结果选择是否输出这个数据,是素数则输出
if (flag) {
System.out.println(i + "\t");
}
}
}
}
案例3:验证码随机生成
public class Test3 {
public static void main(String[] args) {
// 需求:随机生成一个验证码
String code = createCode(5);
System.out.println("您的验证码为:" + code);
}
public static String createCode(int n){
// 建立一个随机数数据库
String code = "";
Random r = new Random();
// 定义一个for循环,循环n次,依次生成一串验证码
for (int i = 0; i < n; i++) {
// 生成随机字符 大小写字母 数字
// 验证码的组成共3种类别,因此定义type的数量为3种
// 进行联动随机数数据库,即r.nextInt( bound:种类数量 );
int type = r.nextInt(3); // 0 1 2
// 进行大小分支分类讨论
switch (type){
case 0:
// 大写字母 (A 65 - Z 65+25) (0-25)+ 65
char ch = (char) (r.nextInt(26) + 65);
code += ch;
break;
case 1:
// 小写字母 (a 97 - z 97+25) (0-25) + 97
char ch1 = (char) (r.nextInt(26) + 97);
code += ch1;
break;
case 2:
// 数字字符
code += r.nextInt(10); // 0-9
break;
}
}
// 返回数值,传递接收
return code;
}
}