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
方块的细微差别
重要的一点:
如果不在if-else
构造中使用花括号,则 theelse
指的是最近的前一个if
.
例子:
我们的代码 | 它将如何运作 |
---|---|
|
|
如果您查看左侧的代码,屏幕输出似乎将是“您不必工作”。但事实并非如此。实际上,else
块和“你不必工作”声明与第二个(更接近的)if
声明相关联。
在右侧的代码中,关联的if
和else
以红色突出显示。此外,花括号的位置很明确,清楚地显示了将执行的操作。当大于时,字符串You don't have to work从不显示。age
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
}
}
显示两个数中的最小值
GO TO FULL VERSION