while ループ

中級 Java

Jim White

Java Developer

while ループの仕組み

  • まず条件を確認
    • 真ならコードを実行
    • 偽ならループ終了
  • 反復: 条件を確認し、次を判断

while ループの模式図

中級 Java

while ループの構文

while (condition) {

  // Run this code

}
  • 構文は if 文に似る
  • if と異なり、複数回実行される
中級 Java

while ループの例

// 5 未満の数を出力
int counter = 1;

while (counter < 5){
  System.out.println(counter);
  counter = counter + 1;
}
1
2
3
4
中級 Java

無限 while ループ

  • 変数更新を忘れる
int counter = 1;

while (counter < 5){
  System.out.println(counter);
  counter = counter + 0;
}

 

➡ プログラムがハングする

  • 条件が常に true
int counter = 1;

while (counter < 5){
  System.out.println(counter);
  counter = counter - 1;
}
中級 Java

更新演算子

int counter = 0;

// Same as counter = counter + 3
counter += 3;

次と同様: -=, *=, /=, ...

中級 Java

break

  • breakwhile を早期終了できるが、最善の実装とは限らない
int counter = 1;
while (counter < 5){
    System.out.println("Counter: " + counter);
    if (counter == 3) {
        break; // Exit the loop when counter is 3
    }
    counter+=2;
}
Counter: 1
Counter: 3
中級 Java

まとめ

// while ループ: 20 未満の偶数を出力
int counter = 2;

while (counter < 20){
  System.out.println(counter);
  counter *= 2;

  // counter が奇数なら終了
  if (counter % 2 == 1){ // counter % 2 は 2 での剰余
    System.out.println("Something went wrong, counter is odd.");
    break;
  }
}
中級 Java

Lass uns üben!

中級 Java

Preparing Video For Download...