특정 횟수만큼 작업을 반복하고 싶을 때 사용
for(초기식; 조건식; 증감식){
초기식에 선언된 변수가 조건식이 참일 동안에
반복할 명령;
ex) 1부터 10까지 출력하기
for(int i = 1; i<=10; i++) {
System.out.println(i);
}
조건이 참일 동안에 ~ 명령을 반복하는 것
조건이 거짓이면 한 번도 실행되지 않는다.
while 조건식 {
반복할 명령;
}
ex) 1~10까지 출력하기
int x = 1;
while(x <=10) {
System.out.println(x);
x++;
1~100사이 숫자 맞히기
import java.util.Random;
import java.util.Scanner;
public class Day02Ex {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Random random = new Random();
int num = random.nextInt(100)+1;
int user = -1;
while(user!=num) {
System.out.print("숫자 입력:");
user = sc.nextInt();
if(user==num) {
System.out.println("정답입니다!");
}
else if(user>num) {
System.out.println("Down!");
}
else {
System.out.println("Up!");
}
}
}
}
한 번은 무조건 실행하고, 조건이 참이라면 명령을 반복한다.
do{
반복할 명령;
} while(조건식);
int i = 100;
do{
System.out.println("적어도 한 번은 출력되는 문장");
}
while(i<10);