1.if
ステートメントの順序
場合によっては、プログラムは、変数の値または式の値に応じて、さまざまなアクションを実行する必要があります。
私たちのタスクが次のようなものだとしましょう:
- 気温が
20
1度以上の場合はシャツを着てください - 気温が 度より高く
10
、 度以下 (または同等)の場合は20
、セーターを着ます - 気温が 度以上
0
、度以下(または同等)の場合は10
、レインコートを着用してください - 気温が
0
1度未満の場合は、コートを着てください。
これをコードでどのように表現できるかは次のとおりです。
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 つの例は同等ですが、2 番目の例の方が理解しやすいです。
2.else
ブロックのニュアンス
重要な点:
構造内で中括弧を使用しない場合if-else
、 はelse
最も近い前の を参照しますif
。
例:
私たちのコード | どのように機能しますか |
---|---|
|
|
左のコードを見ると「作業する必要はありません」という画面出力になるようです。しかしそうではありません。実際には、else
ブロックと「作業する必要はありません」ステートメントは 2 番目の (近い方の)if
ステートメントに関連付けられています。
右側のコードでは、関連するif
と がelse
赤で強調表示されています。さらに、中括弧は明確に配置され、どのようなアクションが実行されるかを明確に示します。が より大きい場合、文字列「You don't have to work」は表示されません。age
60
if-else
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
}
}
2 つの数値の最小値を表示する
GO TO FULL VERSION