## `if`1.陳述順序

• 如果溫度大於`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`方塊的細微差別

``````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");
}``````

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`語句的例子

``````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
}
}``````