Java中的分支结构

分支结构

if结构:一条路
1)语法:
if(boolean){
    语句块-------------基于条件执行的语句
}
2)执行过程:
判断boolean的值:
若为true,则执行语句块(整个结束)
若为false,则直接结束
//1)偶数的判断:
int num = 6;
if(num%2==0){
    System.out.println(num+"是偶数");
}
  
//2)满500打8折
double price = 300.0;
if(price>=500){
    price = price*0.8;
}
System.out.println("最终结算金额为:"+price); //300.0
if…else结构:两条路
1)语法:
if(boolean){
    语句块1
}else{
    语句块2
}
2)执行过程:
判断boolean的值:
若为true,则执行语句块1(整个结束)
若为false,则执行语句块2(整个结束)
3)说明:
语句块1和语句块2,必走其中之一----------21
//1)偶数、奇数的判断:
int num = 5;
if(num%2==0){
    System.out.println(num+"是偶数");
}else{
    System.out.println(num+"是奇数");
}

//2)满500打8折,不满500打9折:
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("输入错误");
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值