中級 Java
Jim White
Java Developer

while (condition) {
// Run this code
}
if 文に似るif と異なり、複数回実行される// 5 未満の数を出力
int counter = 1;
while (counter < 5){
System.out.println(counter);
counter = counter + 1;
}
1
2
3
4
int counter = 1;
while (counter < 5){
System.out.println(counter);
counter = counter + 0;
}
➡ プログラムがハングする
trueint counter = 1;
while (counter < 5){
System.out.println(counter);
counter = counter - 1;
}
int counter = 0;
// Same as counter = counter + 3
counter += 3;
次と同様:
-=,
*=,
/=, ...
break で while を早期終了できるが、最善の実装とは限らない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
// 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