Java 中級
Jim White
Java Developer

while (condition) {
// Run this code
}
if 陳述式if 不同,可重複執行多次// Prints numbers smaller than 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 loop that prints even numbers smaller than 20
int counter = 2;
while (counter < 20){
System.out.println(counter);
counter *= 2;
// Exit while loop if counter is odd
if (counter % 2 == 1){ // counter % 2 is counter modulo 2
System.out.println("Something went wrong, counter is odd.");
break;
}
}
Java 中級