2.1判断语句

if语句

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

if…else语句

  1. if (关系表达式){
  2. 语句体1
  3. }else{
  4. 语句体2
  5. }

if...else if ...else语句

  1. if (关系表达式1){
  2. 语句体1
  3. }else if(判断语句2){
  4. 语句体2
  5. }
  6. ...
  7. ...
  8. }else if(判断语句n){
  9. 语句体n
  10. }else{
  11. 语句n+1
  12. }

2.2选择语句

switch语句

  1. switch(表达式){
  2. case 常量值1:
  3. 语句体1;
  4. break;
  5. case 常量值2:
  6. 语句体2;
  7. break;
  8. ...
  9. ...
  10. default:
  11. 语句体n+1;
  12. break;
  13. }

2.3循环语句

for循环

for (初始条件; 循环检测条件; 循环后更新计数器) {
    // 执行语句
}

for循环还可以缺少初始化语句、循环条件和每次循环更新语句

for each循环

public class Main {
    public static void main(String[] args) {
        int[] ns = { 1, 4, 9, 16, 25 };
        for (int n : ns) {
            System.out.println(n);
        }
    }
}

while循环

while (条件表达式) {
    循环语句
}
// 继续执行后续代码

2.4跳出语句

break

在循环过程中,可以使用break语句跳出当前循环

public class Main {
    public static void main(String[] args) {
        int sum = 0;
        for (int i=1; ; i++) {
            sum = sum + i;
            if (i == 100) {
                break;
            }
        }
        System.out.println(sum);
    }
}

continue

break会跳出当前循环,也就是整个循环都不会执行了。而continue则是提前结束本次循环,直接继续执行下次循环

public class Main {
    public static void main(String[] args) {
        int sum = 0;
        for (int i=1; i<=10; i++) {
            System.out.println("begin i = " + i);
            if (i % 2 == 0) {
                continue; // continue语句会结束本次循环
            }
            sum = sum + i;
            System.out.println("end i = " + i);
        }
        System.out.println(sum); // 25
    }
}