Java else 关键字

实例

如果条件为 false,则使用 else 语句指定要执行的代码块。

  1. public class Main {
  2. public static void main(String[] args) {
  3. int time = 20;
  4. if (time < 18) {
  5. System.out.println("Good day.");
  6. } else {
  7. System.out.println("Good evening.");
  8. }
  9. }
  10. }

定义与用法

else 语句指定在 if 语句中条件为 false 时要执行的 Java 代码块。

Java 有以下条件语句:

  • 如果指定的条件为 true,则使用 if 指定要执行的代码块
  • 如果相同条件为 false,则使用 else 指定要执行的代码块
  • 如果第一个条件为 false,则使用 else if 指定要判断的新条件
  • 使用 switch 指定要执行的许多可选代码块

更多实例

实例

如果第一个条件为 false,则使用 else if 语句指定新条件

  1. public class Main {
  2. public static void main(String[] args) {
  3. int time = 22;
  4. if (time < 10) {
  5. System.out.println("Good morning.");
  6. } else if (time < 20) {
  7. System.out.println("Good day.");
  8. } else {
  9. System.out.println("Good evening.");
  10. }
  11. }
  12. }

关联页面

阅读更多的条件语句,访问本站的 Java If…Else

分类导航