分支结构
if结构:一条路
1)语法:
if(boolean){
语句块-------------基于条件执行的语句
}
2)执行过程:
判断boolean的值:
若为true,则执行语句块(整个结束)
若为false,则直接结束
int num = 6;
if(num%2==0){
System.out.println(num+"是偶数");
}
double price = 300.0;
if(price>=500){
price = price*0.8;
}
System.out.println("最终结算金额为:"+price);
if…else结构:两条路
1)语法:
if(boolean){
语句块1
}else{
语句块2
}
2)执行过程:
判断boolean的值:
若为true,则执行语句块1(整个结束)
若为false,则执行语句块2(整个结束)
3)说明:
语句块1和语句块2,必走其中之一----------2选1
int num = 5;
if(num%2==0){
System.out.println(num+"是偶数");
}else{
System.out.println(num+"是奇数");
}
double price = 300.0;
if(price>=500){
price = price*0.8;
}else{
price = price*0.9;
}
System.out.println("最终结算金额为:"+price);
if…else if结构:多条路
1)语法:
if(boolean-1){
语句块1
}else if(boolean-2){
语句块2
}else if(boolean-3){
语句块3
}else{
语句块4
}
2)执行过程:
判断boolean-1,若为true则执行语句块1(结束),若为false则
再判断boolean-2,若为true则执行语句块2(结束),若为false则
再判断boolean-3,若为true则执行语句块3(结束),若为false则执行语句块4(结束)
3)说明:
语句块1/2/3/4,必走其中之一-------多选1
import java.util.Scanner;
public class ScoreLevel {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("请输入成绩:");
double score = scan.nextDouble();
if(score<0 || score>100){
System.out.println("成绩不合法");
}else if(score>=90){
System.out.println("A-优秀");
}else if(score>=80){
System.out.println("B-良好");
}else if(score>=60){
System.out.println("C-中等");
}else{
System.out.println("D-不及格");
}
}
}
switch…case结构:
- 优点:效率高、结构清晰
- 缺点:只能对整数判断相等
- break:跳出switch
>switch后数据的类型可以为:byte,short,char,int,String,枚举类型
import java.util.Scanner;
public class CommandBySwitch {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("请选择功能: 1.存款 2.取款 3.查询余额 4.退卡");
int command = scan.nextInt();
switch(command){
case 1:
System.out.println("存款操作...");
break;
case 2:
System.out.println("取款操作...");
break;
case 3:
System.out.println("查询余额操作...");
break;
case 4:
System.out.println("退卡操作...");
break;
default:
System.out.println("输入错误");
}
}
}