중급 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 is counter modulo 2
System.out.println("Something went wrong, counter is odd.");
break;
}
}
중급 Java