
for : 반복횟수를 알 때
while : 반복횟수를 모를 때
while과 for는 호환 가능
while (조건식) {
}
반복횟수를 모를 때 주로 사용
예제)
public static void main(String[] args) {
int i= 5;
while(i!=0) {
i--;
System.out.println(i + " - I can do it.");
}
}
💡while(true) { : 무한 반복문 (조건식이 계속 참이기 때문에), break;가 들어가 줘야함
ex) 예제 - 1~100 랜덤인 수 맞추기
import java.util.Scanner;
class Ex4_15 {
public static void main(String[] args) {
int input = 0, answer = 0;
answer = (int)(Math.random() * 100) + 1;
Scanner sc = new Scanner(System.in);
do {
System.out.print("1과 100사이의 정수를 입력");
input = sc.nextInt();
if(input > answer) {
System.out.println("더 작은 수로 다시 시도해보세요.");
} else if(input < answer) {
System.out.println("더 큰 수로 다시 시도해보세요.");
}
} while(input!=answer);
System.out.println("정답입니다.");
}
}
자신과 가장 가까운 조건문을 빠져나감
class Ex4_16 {
public static void main(String[] args) {
int sum = 0;
int i = 0;
while(true) { // for문으로 바꾸려면 for(;;) 하면됨
if(sum > 100)
break;
++i;
sum += i;
} // end of while
System.out.println("i=" + i);
System.out.println("sum=" + sum);
}
}
💡while 안에 if 조건식이 참이 되면 break;
💡sum이 100을 초과하면 break;가 걸리면서 while 종료
❗ while 조건식 생략 불가
자신이 포함된 반복문의 끝으로 이동, 다음 반복으로 넘어감
전체 반복 중 특정 조건시 반복을 건너 뛸 때 유용
class Ex4_17 {
public static void main(String[] args) {
for(int i=0;i <= 10;i++) {
if (i%3==0)
continue;
System.out.println(i);
} // 💡조건식이 참일때 continue가 여기로 옴
}
}
💡if 안의 조건식이 참이 될 때 건너 뛴다.
💡결과값 1 2 4 5 7 8 10 (3으로 나눌경우 0이 되면 if문을 나가니까) print되지 않음
import java.util.Scanner;
class Ex4_18 {
public static void main(String[] args) {
int menu = 0;
int num = 0;
Scanner scanner = new Scanner(System.in);
while(true) {
System.out.println("(1) square");
System.out.println("(2) square root");
System.out.println("(3) log");
System.out.print("원하는 메뉴 (1~3)를 선택하세요. (종료 : 0)");
String tmp = scanner.nextLine();
menu = Integer.parseInt(tmp);
if(menu==0) {
System.out.println("프로그램을 종료합니다.");
break;
} else if (!(1 <= menu && menu <= 3)) {
System.out.println("메뉴를 잘못 선택하셨습니다. (종료는 0)");
continue;
}
System.out.println("선택하신 메뉴는 "+ menu +"번 입니다.");
}
}
}