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 + "秒");
            }
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/hq82/p/11627382.html