选择结构
if单选择结构
-
我们很多时候需要去判断一个东西是否可行,然后我们才去执行,这样一个过程在程序中用 if 语来表示
-
语法:
public class IfDemo01 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入内容:");
String s = scanner.nextLine();
if (s.equals("Hello")){
System.out.println(s);
}
System.out.println("End");
scanner.close();
}
}
if双选择结构
-
那现在有个需求,公司要收购一个软件,成功了,给人支付100w,失败了,自己找人开发。这样的需求用一个if就搞不定了,我们需要有两个判断,需要一个双选择结构,所以就有了if-else结构。
-
语法:
public class IfDemo04 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入金额");
int money = scanner.nextInt();
if (money>1000_000){
System.out.println("成功");
}else {
System.out.println("自己开发");
}
scanner.close();
}
}
if多选择结构
-
我们发现刚才的代码不符合实际情况,真实情况还可能存在ABCD,存在区间多级判断。比如90-100就是A,80-90就是B...等等,在生活中我们很多时候的选择也不仅仅只有两个,所以我们需要一个多选择结构来处理这类问题!
-
语法:
public class IfDemo03 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
/*
if 语句至多有 1 个 else 语句, else 语句在所有的 else if 语句之后。
if 语句可以有若干个 else if 语句 ,它们必须在 else 语句之前。
一旦其中一个 else if 语句检测为 true ,其他的 else if 以及 else 语句都将跳过执行。
*/
System.out.println("请输入成绩:");
int score = scanner.nextInt();
if (score==100){
System.out.println("恭喜满分");
}else if (score<100 && score>=90){
System.out.println("A");
}else if (score<90 && score>=800){
System.out.println("B");
}else if (score<80 && score>=70){
System.out.println("C");
}else if (score<70 && score>=60){
System.out.println("D");
}else if (score<60 && score>=0){
System.out.println("不及格");
} else {
System.out.println("成绩不合法");
}
scanner.close();
}
}
嵌套的if结构
-
使用嵌套是的if...else语句是合法的。也就是说你可以在另一个if或者else if语句中使用if或者else if语句。你可以像if语句一样嵌套式else if...else。
语法:
if(布尔表达式 1){
//如果不二表达式 1 的值为true执行代码
if(布尔表达式 2){
//如果布尔表达式 2 的值为true执行代码
}
}
switch多选择结构
-
多选择结构还有一个实现方式就是switch case 语句
-
switch case 语句判断一个变量与一系列值中某个值是否相等每个值称为一个分支。
public class SwitchDemo01 {
public static void main(String[] args) {
//case 穿透 switch 匹配一个具体的值
char grade = 'F';
switch (grade){
case 'A':
System.out.println("优秀");
break;//可选
case 'B':
System.out.println("良好");
break;
case 'C':
System.out.println("及格");
break;
case 'D':
System.out.println("再接再厉");
break;
case 'E':
System.out.println("挂科");
break;
default:
System.out.println("未知等级");
}
}
}
-
switch 语句中的变量类型可以是:
-
byte、short、int或者char。
-
从JavaSE7开始
-
switch支持字符串String类型了
-
同时case标签必须为字符串常量或字面。
-
public class SwitchDemo02 {
public static void main(String[] args) {
String name = "sunlight";
//JDK7的新特性,表达结果可以是字符串
//字符的本质还是数字
//反编译 Java---class(字节码文件)---反编译(IDEA)
switch (name){
case"猫病先生":
System.out.println("猫病先生");
break;
case "sunlight":
System.out.println("sunlight");
break;
default:
System.out.println("弄撒内?");
}
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)