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 Syntax,  等級 4課堂 1
上鎖
This age doesn't work for me…
Sometimes we all want to change our age. First, they don't want to sell you cigarettes or beer. Then your hair starts thinning and your back aches! A programmer may not have control over time, but he or she has total control over data in programs. In this task, we correct an error so that a Person object's age variable receives a different value.

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
   }
}
顯示兩個數中的最小值