1.ifステートメントの順序

場合によっては、プログラムは、変数の値または式の値に応じて、さまざまなアクションを実行する必要があります。

私たちのタスクが次のようなものだとしましょう:

  • 気温が201度以上の場合はシャツを着てください
  • 気温が 度より高く10、 度以下 (または同等)の場合は20、セーターを着ます
  • 気温が 度以上0、度以下(または同等)の場合は10、レインコートを着用してください
  • 気温が01度未満の場合は、コートを着てください。

これをコードでどのように表現できるかは次のとおりです。

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

例:

私たちのコード どのように機能しますか
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");
}

左のコードを見ると「作業する必要はありません」という画面出力になるようです。しかしそうではありません。実際には、elseブロックと「作業する必要はありません」ステートメントは 2 番目の (近い方の)ifステートメントに関連付けられています。

右側のコードでは、関連するifと がelse赤で強調表示されています。さらに、中括弧は明確に配置され、どのようなアクションが実行されるかを明確に示します。が より大きい場合、文字列「You don't have to work」は表示されません。age60


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.

if-else3.ステートメントの使用例

このステートメントを詳しく調べたので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 つの数値の最小値を表示する