4. java 流程控制

一、判断语句

1. if 判断
if(关系表达式){
    语句体;
}

int age = 16;
if(age >= 18){
    System.out.println("hello");
}
2. if-else判断
if(判断条件){
    语句体1;
} else{
    语句体2;  
}

int num = 13;
if(num % 2 == 0){
    System.out.println("偶数");
} else{
    System.out.println("基数");
}
3. if-else if-else
if(判断条件1){
    执行语句1;
} else if(判断条件2){
    执行语句2;  
}
...
else if(判断条件n){
    执行语句n;  
} else{
    执行语句n+1;
}

二、选择语句

switch(表达式){
    case 常量值1:
        语句体1;
        break;
    case 常量值2:
        语句体1;
        break;
    ...
    default:
        语句体n+1;
        break;
}

三、循环语句

1. for 循环
// 次数确定的场景,多采用for
for(初始化表达式1; 布尔表达式2; 步进表达式3){
    循环体;
}

for(int i=1; i<10; i++){
    System.out.println("hello");
}
2. while 循环
while(条件判断){
    循环体;
}

初始化语句;
while(条件判断){
    循环体;
    步进语句;
}

int i = 1;
while(i<=10){
    System.out.println("hello");
    i++;
}
3. do-while 循环
初始化表达式;
do{
    循环体;
    步进语句;
}while(布尔表达式);

int i = 1;
do{
    System.out.println("hello");
    i++;
}while(i<=10);
4. 例子
public class test {
    public static void main(String[] args) {
        int sum = 0;
        for(int i=1; i<=100;i++){
            if(i % 2 == 0){
                System.out.println(i);
                sum += i;
            }
        }
        System.out.println(sum);
    }
}
5. break 语句
public class test {
    public static void main(String[] args) {
        for(int i=1; i<=100;i++){
            if(i == 90){
                // 如果i是90,打断整个循环
                break;
            }
            System.out.println(i);
        }
    }
}
6. continue 语句
public class test {
    public static void main(String[] args) {
        for(int i=1; i<=100;i++){
            if(i == 90){
                // 如果i是90,打断本次循环,继续下一次循环
                continue;
            }
            System.out.println(i);
        }
    }
}
7. 死循环
public class test {
    public static void main(String[] args) {
        while(true){
            System.out.println("hello world");
        }
    }
}
8. 循环嵌套
public class test {
    public static void main(String[] args) {
        for (int i = 0; i < 60; i++) {
            for (int j = 0; j < 60; j++) {
                System.out.println("当前时间:" + i + "时" + j + "秒");
            }
        }
    }
}

转载于:https://www.cnblogs.com/hq82/p/11627382.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值