选择结构
选择结构
-
if单选择结构
public class IfDemo01 { public static void main(String[] args) { Scanner scanner=new Scanner(System.in); System.out.println("请输入内容:"); String s =scanner.nextLine(); //equals:判断字符是否想等 if (s.equals("Hello")){ System.out.println(s); } System.out.println("End"); scanner.close(); } } -
if双选择结构
public class IfDemo02 {
public static void main(String[] args) {
//考试分数大于等于60分就是及格,小于60就是不及格
Scanner scanner=new Scanner(System.in);
System.out.println("请输入成绩:");
int score=scanner.nextInt();
if (score>=60){
System.out.println("及格");
}else{
System.out.println("不及格");
}
scanner.close();
}
}
- if多选择结构
public class IfDemo03 {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
/*
* if语句之多有1个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>=80){
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结构
-
switch多选择结构
switch多选择结构
switch多选择结构
- 多选择结构还有一个实现方式就是switch case语句
- switch case语句判断一个变量与一系列值中某个值是否想等,每个值称为一个分支。


case后基本要跟一个break,不然会输出其他输出:

grade为B时就会输出后面的输出,在case'D'后加一个break:

输出D后就结束了运行。
switch语句中的变量类型
- byte、short、int或者char。(八大类型)
- 从Java SE 7开始
- switch支持字符串String类型了
- 同时case标签必须为字符串常量或字面量。
public class SwitchDemo02 {
public static void main(String[] args) {
String name="张三";
//JDk7的新特性,表达式结果可以是字符串!!!
//字符的本质还是数字
//反编译 java---class(字节码文件)----反编译(IDEA)
switch(name){
case"张三":
System.out.println("张三");
break;
case"李四":
System.out.println("李四");
break;
default:
System.out.println("无");
}
}
}
浙公网安备 33010602011771号