Skip to content

流程控制

if 语句

java
public class ScoreAssess {
    public static void main(String[] args) {
        System.out.println("请输入分数:");
        Scanner sc = new Scanner(System.in);
        int score = sc.nextInt();
        if (score >= 90) {
            System.out.println("优秀");
        } else if (score >= 80) {
            System.out.println("良好");
        } else if (score >= 60) {
            System.out.println("中等");
        } else {
            System.out.println("不及格");
        }
    }
}

switch 语句

java
public class WeekDemo {
    public static void main(String[] args) {
        System.out.println("请输入星期:");
        Scanner sc = new Scanner(System.in);
        int week = sc.nextInt();
        switch (week) {
            case 1:
                System.out.println("星期一");
                break;
            case 2:
                System.out.println("星期二");
                break;
            case 3:
                System.out.println("星期三");
                break;
            case 4:
                System.out.println("星期四");
                break;
            case 5:
                System.out.println("星期五");
                break;
            case 6:
                System.out.println("星期六");
                break;
            case 7:
                System.out.println("星期日");
                break;
            default:
                System.out.println("输入错误");
        }
    }
}

while 循环

java
public class WhileDemo {
	public static void main(String[] args) {
		int i = 1;
		while (i <= 10) {
			System.out.println(i);
			i++;
		}
	}
}

do-while 循环

java
public class DoWhileDemo {
	public static void main(String[] args) {
		int i = 1;
		do {
			System.out.println(i);
			i++;
		} while (i <= 10);
	}
}

for 循环

java
public class ForDemo {
	public static void main(String[] args) {
		for (int i = 1; i <= 10; i++) {
			System.out.println(i);
			i++;
		}
	}
}

break 语句

  1. break 语句用于跳出当前循环的执行。
  2. break 语句只能用于跳出当前循环,不能跳出多层循环。
  3. break 语句既能用在循环里,也能用在 switch 语句里。

continue 语句

  1. continue 语句只能用在循环里
  2. continue 语句用于跳过当前循环的剩余语句,继续下一次循环。

break 关键字补充

break 关键字分别表示跳出 switch 结构 或者 循环结构

默认情况下 只会中断离其最近的结构

也可以自定义标记 使用 break 关键字 跳出指定标记的结构

java
/**
 * break关键字分别表示跳出switch结构 或者 循环结构
 * 默认情况下 只会中断离其最近的结构
 * 也可以自定义标记 使用break 关键字 跳出指定标记的结构
 */
public class TestBreak {
    public static void main(String[] args) {

        abc: for(int i = 1; i <= 5; i++) {
            for (int j = 1; j <= 5; j++) {
                System.out.print(j + "\t");
                if (j == 3) {
                    break abc;
                }
            }
            System.out.println();
        }
    }
}

Keep Reading, Keep Writing, Keep Coding