判断语句

if-else语句

与C++、Python中类似。

例如:

package com.yxc;

import java.util.Scanner;

public class Main {
   public static void main(String[] args) {
       Scanner sc = new Scanner(System.in);
       int year = sc.nextInt();
       if (year % 100 == 0) {
           if (year % 400 == 0)
               System.out.printf("%d是闰年\n", year);
           else
               System.out.printf("%d不是闰年\n", year);
       } else {
           if (year % 4 == 0)
               System.out.printf("%d是闰年\n", year);
           else
               System.out.printf("%d不是闰年\n", year);
       }
   }
}

switch语句

与C++中类似。

package com.yxc;

import java.util.Scanner;

public class Main {
   public static void main(String[] args) {
       Scanner sc = new Scanner(System.in);
       int day = sc.nextInt();
       String name;
       switch (day) {
           case 1:
               name = "Monday";
               break;
           case 2:
               name = "Tuesday";
               break;
           case 3:
               name = "Wednesday";
               break;
           case 4:
               name = "Thursday";
               break;
           case 5:
               name = "Friday";
               break;
           case 6:
               name = "Saturday";
               break;
           case 7:
               name = "Sunday";
               break;
           default:
               name = "not valid";
       }
       System.out.println(name);
   }
}

逻辑运算符与条件表达式

与C++、Python类似。

例如:

package com.yxc;

import java.util.Scanner;

public class Main {
   public static void main(String[] args) {
       Scanner sc = new Scanner(System.in);
       int year = sc.nextInt();
       if (year % 100 != 0 && year % 4 == 0 || year % 400 == 0)
           System.out.printf("%d是闰年\n", year);
       else
           System.out.printf("%d不是闰年\n", year);
   }
}

注意一点是 java中 int不能作为bool值来判断

所以不能写成 year % 100 && year % 4 0 || year % 400 0

练习题

  <a href="/vault/2-Learning/05-%E9%A1%B9%E7%9B%AE/04-SpringBoot%E6%A1%86%E6%9E%B6%E8%AF%BE/01-java%E8%AF%AD%E6%B3%95/02-%E5%88%A4%E6%96%AD%E8%AF%AD%E5%8F%A5/01-%E5%80%8D%E6%95%B0">倍数</a>

零食

区间 游戏时间 动物


项目分区导航钞票 ⬅️ | 00-判断语句 | ➡️ 倍数