分支结构
if分支
if 第一种形式
// 需求:测量用户体温,发现体温高于37度就报警。
double temp = 38;
if (temp > 37)
{ System.out.println("这个人体温不正常,快把他抓走");
System.out.println("这个人体温不正常,快把他抓走");
System.out.println("这个人体温不正常,快把他抓走");
}
System.out.println("我是代码的剩余部分");
if 第二种形式
// 需求2:发红包,你的钱包余额是99元,现在要发出90元
// 如果钱够触发发红包的动作,如果钱不够,则提示:余额不足
。 public static void main(String[] args) {
// 需求2:发红包,你的钱包余额是99元,现在要发出90元
// 如果钱够触发发红包的动作,如果钱不够,则提示:余额不足
。 System.out.println("我要开始发红包了");
double balance = 89;
if (balance > 90) {
balance -= 90;
System.out.println("你的余额是" + balance);
} else {
System.out.println("余额不足");
}
System.out.println("继续执行main方法");
}
if 第三种形式
// 需求3:某个公司有一个绩效系统,根据员工的打分输出对应的绩效级别。
[0,60) D [60,80) C [80,90) B [90,100] A
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入员工打分成绩");
double score = sc.nextDouble();
// 需求3:某个公司有一个绩效系统,根据员工的打分输出对应的绩效级别。
[0,60) D [60,80) C [80,90) B [90,100] A
if (score >= 0 && score < 60)
{ System.out.println("员工绩效级别:D");
} else if (score < 80) {
System.out.println("员工绩效级别:C");
} else if (score < 90) {
System.out.println("员工绩效级别:B");
} else if (score <= 100) {
System.out.println("员工绩效级别:A");
} else {
System.out.println("你输入的成绩不合理");
}
System.out.println("继续执行main方法");
}
if 使用的几个常见问题
第1个问题:if的()后面不能写分号 ; 否则if下面的语句与if无关
switch分支
String week = "周三";
switch (week){
case "周一":
System.out.println("埋头苦干,解决bug");
break;
case "周二":
System.out.println("请求大牛程序员帮忙");
break;
case "周三":
System.out.println("今晚啤酒、龙虾、小烧烤");
break;
case "周四":
System.out.println("主动帮助新来的女程序解决bug");
break;
case "周五":
System.out.println("今晚吃鸡"); break;
case "周六":
System.out.println("与王婆介绍的小芳相亲");
break;
case "周日":
System.out.println("郁郁寡欢、准备上班");
break;
default:
System.out.println("您输入的星期信息不存在~~~");
}
switch分支新特性
public static void main(String[] args) {
// 先输入年份,在输入一个月份,返回这个月多少天
// 31 30 29 28 31 1,3,5,7,8,10,12 30 4, 6 , 9, 11 2 闰年 29天 平年 28天
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个年份:");
int year = sc.nextInt();
System.out.println("请输入一个月份:");
int month = sc.nextInt();
// int temp = 12;
// switch 新特性 -> 箭头表达式
int days = 0;//int days = switch (month)
switch (month) {
case 1, 3, 5, 7, 8, 10, 12 ->
days = 31;
case 4, 6, 9, 11 ->
days = 30;
case 2 -> {
// 判断 year 是否是闰年
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
days = 29; yield 29;
} else {
days = 28; yield 28;
}
}
default ->
days = -1;
}
if (days == -1)
{ System.out.println("输入的月份不正确");
} else {
System.out.println("这个月" + days + "天");
}
// System.out.println(days == -1 ? "输入的月份不正确" : "这个月" + days + "天");
}