if1.语句顺序

有时,程序需要根据变量的值或表达式的值执行许多不同的操作。

假设我们的任务是这样的:

  • 如果温度大于20度,则穿上衬衫
  • 如果温度大于10度且小于(或等于)20,则穿上毛衣
  • 如果温度大于0度且小于(或等于)10,则穿上雨衣
  • 如果温度低于0度,则穿上外套。

这是如何用代码表示的:

int temperature = 9;

if (temperature > 20) {
   System.out.println("put on a shirt");
} else { // Here the temperature is less than (or equal to) 20
   if (temperature > 10) {
      System.out.println("put on a sweater");
   } else { // Here the temperature is less than (or equal to) 10
      if (temperature > 0) {
         System.out.println("put on a raincoat");
      } else // Here the temperature is less than 0
         System.out.println("put on a coat");
   }
}

If-else语句可以相互嵌套。这使得在程序中实现相当复杂的逻辑成为可能。

但是,程序员通常会以不同的方式编写此构造:

int temperature = 9;

if (temperature > 20) {
   System.out.println("put on a shirt");
} else if (temperature > 10) { // Here the temperature is less than (or equal to) 20
   System.out.println("put on a sweater");
} else if (temperature > 0) { // Here the temperature is less than (or equal to) 10
   System.out.println("put on a raincoat");
} else { // Here the temperature is less than 0
   System.out.println("put on a coat");
}

给出的两个例子是等价的,但第二个例子更容易理解。


2.else方块的细微差别

重要的一点:

如果不在if-else构造中使用花括号,则 theelse指的是最近的前一个if.

例子:

我们的代码 它将如何运作
int age = 65;

if (age < 60)
   if (age > 20)
      System.out.println("You must work");
else
   System.out.println("You don't have to work");
int age = 65;

if (age < 60) {
   if (age > 20)
     System.out.println("You must work");
   else
     System.out.println("You don't have to work");
}

如果您查看左侧的代码,屏幕输出似乎将是“您不必工作”。但事实并非如此。实际上,else块和“你不必工作”声明与第二个(更接近的)if声明相关联。

在右侧的代码中,关联的ifelse以红色突出显示。此外,花括号的位置很明确,清楚地显示了将执行的操作。当大于时,字符串You don't have to work从不显示。age60


4
任务
Java 语法,  第 4 级课程 1
已锁定
这个年龄不适合我...
有时我们所有人都想更改自己的年龄。例如,当他们不想向你出售香烟或啤酒时。或者,当你的头发开始稀疏,背部又酸又痛时!程序员可能无法控制时间,但是他们可以完全控制程序中的数据。在此任务中,我们将纠正一个错误,以使 Person 对象的 age 变量收到不同的值。

3.使用if-else语句的例子

由于我们if-else很好地探索了这个陈述,让我们举一个例子:

import java.util.Scanner;
public class Solution {
   public static void main(String[] args) {
     Scanner console = new Scanner(System.in); // Create a Scanner object
     int a = console.nextInt(); // Read the first number from the keyboard
     int b = console.nextInt(); // Read the second number from the keyboard
     if (a < b)                   // If a is less than b
       System.out.println(a);     // we display a
     else                         // otherwise
       System.out.println(b);     // we display b
   }
}
显示两个数中的最小值