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
方塊的細微差別
重要的一點:
如果不在if-else
構造中使用花括號,則 theelse
指的是最近的前一個if
.
例子:
我們的代碼 | 它將如何運作 |
---|---|
|
|
如果您查看左側的代碼,屏幕輸出似乎將是“您不必工作”。但事實並非如此。實際上,else
塊和“你不必工作”聲明與第二個(更接近的)if
聲明相關聯。
在右側的代碼中,關聯的if
和else
以紅色突出顯示。此外,花括號的位置很明確,清楚地顯示了將執行的操作。當字符串You don't have to work never displayed when age
is greater than時60
?
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
}
}
顯示兩個數中的最小值