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

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

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