Java
[Java] while 반복문
이뮨01
2025. 7. 8. 15:06
while 반복문을 배우다.
while 반복문
while은 반복의 횟수가 정해지지 않은 경우 사용한다. 무한 반복을 방지하기 위해서 조건이 false가 되는 것을 실행문에서 작성해 주거나 조건이 항상 true일 경우 실행문에서 if 조건문과 break를 사용해서 while 반복문을 빠져나가는 작업을 해야 한다.
break는 즉시 그 반복문을 벗어나고 반복문이 끝난다.
continue는 즉시 다음 반복으로 넘어간다. 반복문을 벗어나는 것이 아니다.
while은 사용자에게 올바른 입력을 받을 때까지 입력값을 요청할 때 사용할 수 있다.
package ch04_control;
import java.util.Scanner;
public class While06 {
/*
* While문은 반복횟수를 모르는 경우 사용
* - 조건문이 만족하는 동안 반복
* - 조건문 true → 무한 반복
* ㄴ if + break문과 함께 사용할 것!
* while(조건) {
* 실행문;
* }
*
* continue & break
* - for, while 모두 사용 가능
* - break → 즉시 반복문을 빠져 나감
* - continue → 즉시 다음 반복문으로 넘어감
*/
public static void main(String[] args) {
// 사용자가 올바른 값을 입력하지 않은 경우!
// - 올바른 값은 1 ~ 5
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("번호: ");;
int num = sc.nextInt();
if (num >= 1 && num <= 5) {
break;
} else {
System.out.println("올바른 값을 입력하세요.");
}
}
}
}
for문과 while문 비교
반복 횟수가 정해진 반복문 for문을 while문으로도 만들 수 있다.
package ch04_control;
public class While07 {
public static void main(String[] args) {
// for문 활용 구구단 2단
System.out.println("for문 구구단 2단");
for (int i = 1; i < 10; i++) {
System.out.println("2 x " + i + " = " + 2 * i);
}
// while문 활용 구구단 2단
System.out.println("while문 구구단 2단");
int j = 1;
while(j < 10) {
System.out.println("2 x " + j + " = " + 2 * j);
j++;
}
}
}