큐범
Just do debug
큐범
전체 방문자
오늘
어제
  • 전체보기 (128)
    • 회고 (4)
    • JAVA (16)
      • JAVA 기초 (18)
      • JAVA Algorithm, Datastruct (13)
    • Spring (11)
    • Micro Service Architecture (3)
    • JPA (6)
    • gRPC (4)
    • Network (8)
    • Process (7)
    • Cloud (4)
    • Python (10)
    • Web(vue) (2)
    • UMC (1)
    • DB (9)
    • CS (1)
    • Clean Code (1)
    • TDD (9)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

인기 글

최근 댓글

최근 글

hELLO · Designed By 정상우.
큐범

Just do debug

JAVA/JAVA 기초

[JAVA 기초] 반복문(while)

2021. 7. 21. 10:46

while문

for문에 비해 while문은 구조가 간단하다. while문은 '참(true)인 동안', 즉 조건식이 거짓이 될 때까지 반복한다.

while(조건식){

반복

}

for문과 while문의 비교

for(int i=1; i<=10; i++) {
			System.out.println(i);
		}

int i=1;
		while(i<=10) {
			System.out.println(i);
			i++;
		}

다음의 반복문은 동일한 결과를 갖는다. 초기화나 증감식이 필요하지 않는 경우에는 while문이 대부분 사용된다. 다음의 예시들은 while문이 적합한 경우들이다.

public static void main(String[] args) {
		int i = 5;
		while(i-- != 0) {
			System.out.println(i + " - i can do it!");
		}
	}
//결과
4 - i can do it!
3 - i can do it!
2 - i can do it!
1 - i can do it!
0 - i can do it!
public static void main(String[] args) {
		int i=11;
		
		System.out.println("카운트 다운을 시작합니다.");
		
		while(i-- != 0) {
			System.out.println(i);
			for(int j=0; j<2_000_000_000; j++) {
				;
			}
		}
		System.out.println("GAME OVER");
		
	}

//결과
카운트 다운을 시작합니다.
10
9
8
7
6
5
4
3
2
1
0
GAME OVER
public static void main(String[] args) {
		int sum = 0;
		int i = 0;
		
		while((sum += ++i) <= 100) {
			System.out.printf("%d - %d%n", i, sum);
		}
		
	}

 

num num%10 sum = sum + num%10 num = num/10
12345 5 5 = 0 + 5 1234=12345/10
1234 4 9 = 5 + 4 123=1234/10
123 3 12 = 9 + 3 12=123/10
12 2 14 = 12 + 2 1=12/10
1 1 15 = 14 + 1 0=1/10
0 - - -
public static void main(String[] args) {
		int sum = 0;
		int i = 0;
		
		while((sum += ++i) <= 100) {
			System.out.printf("%d - %d%n", i, sum);
		}
	}
//결과
1 - 1
2 - 3
3 - 6
4 - 10
5 - 15
6 - 21
7 - 28
8 - 36
9 - 45
10 - 55
11 - 66
12 - 78
13 - 91
public static void main(String[] args) {
		int num;
		int sum = 0;
		boolean flag = true;
		Scanner scanner = new Scanner(System.in);
		
		System.out.println("합계를 구할 숫자를 입력해주세요. (끝내려면 0을 입력)");
		
		while(flag) {
			System.out.print(">>");
			
			String tmp = scanner.nextLine();
			num = Integer.parseInt(tmp);
			
			if(num != 0) {
				sum += num;
			}else {
				flag = false;
			}
		}
		System.out.println("합계: "+sum);
		
	}
//결과
합계를 구할 숫자를 입력해주세요. (끝내려면 0을 입력)
>>1234
>>1234
>>0
합계: 2468

do-while문

do-while문은 while문의 변현으로 기본적인 구조는 while문과 같으나 조건식과 블럭의 순서를 바꿔놓은 것이다. 그래서 while문과 반대로 블럭{}을 먼저 수행 후에 조건식을 평가한다.

do{

조건식의 연산결과가 참일 될 때까지 수행될 문장

} while(조건식);

public static void main(String[] args) {
		int input = 0, answer = 0;
		
		answer = (int) (Math.random()*100)+1;
		Scanner scanner =new Scanner(System.in);
		
		do {
			System.out.print("1과 100사이의 정수를 입력하세요 : ");
			input = scanner.nextInt();
			
			if(input > answer) {
				System.out.println("더 작은 수로 입력해주세요");
			}else if (input < answer) {
				System.out.println("더 큰 수로 입력해주세요");
			}
		}while(input !=answer);
		System.out.println("정답입니다.");
	}
//결과
1과 100사이의 정수를 입력하세요 : 1
더 큰 수로 입력해주세요
1과 100사이의 정수를 입력하세요 : 11
더 큰 수로 입력해주세요
1과 100사이의 정수를 입력하세요 : 15
더 큰 수로 입력해주세요
1과 100사이의 정수를 입력하세요 : 65
정답입니다.
public static void main(String[] args) {
		for(int i=1; i<=100; i++) {
			System.out.printf("i=%d", i);
			
			int tmp = i;
			
			do {
				// tmp%10이 3의 배수인지 확인
				if(tmp%10%3==0 && tmp%10!=0)
					System.out.print("짝");
			}while((tmp/=10)!=0);
			System.out.println();
		}	
	}
//결과
i=1
i=2
i=3짝
i=4
i=5
i=6짝
i=7
i=8
i=9짝
...
i=99짝짝
i=100

break문

public static void main(String[] args) {
		int sum = 0;
		int i = 0;
		
		while(true) {
			if(sum>100)
				break;
			++i;
			sum += i;
		}
		System.out.println("i="+i);
		System.out.println("sum="+sum);	
	}
//결과
i=14
sum=105

숫자를 1부터 계속 더해 나가서 몇까지 더하면 합이 100을 넘는지 알아내는 코드이다. i의 값을 1부터 1씩 계속 증가하며 sum에 저장한다. sum의 값이 100을 넘으면 if문의 조건식이 참이므로 break문이 수행되어 자신이 속한 반복문을 벗어난다.

continue문

public static void main(String[] args) {
		for(int i=0; i<=10; i++) {
			if(i%3==0)
				continue;
			System.out.println(i);
		}
		
	}
//결과
1
2
4
5
7
8
10
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");
			
			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+"번 입니다.");
		}
		
	}
//결과
(1) square
(2) square root
(3) log
3
선택하신 메뉴는 3번 입니다.
(1) square
(2) square root
(3) log

이름 붙은 반복문

public static void main(String[] args) {
		Loop1 : for(int i=2; i<=9; i++) {
				for(int j=1; j<=9; j++) {
					if(j==5)
						break Loop1;
//					break;
//					continue Loop1;
//					continue;
					System.out.println(i+"*"+j+"="+i*j);
				}
				System.out.println();
		}
		
	}
//결과
2*1=2
2*2=4
2*3=6
2*4=8
public static void main(String[] args) {
		int menu = 0, num = 0;
		
		Scanner scanner = new Scanner(System.in);
		
		outer:
		while(true) {
			System.out.println("(1) square");
			System.out.println("(2) square root");
			System.out.println("(3) log");
			System.out.println("원하는 메뉴(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;
			}
			
			for(;;) {
				System.out.print("계산할 값을 입력해주세요. (계산종료 0, 전체종료:99) : ");
				tmp =  scanner.nextLine();
				num = Integer.parseInt(tmp);
				
				if(num==0)
					break;
				if(num==99)
					break outer; //모든 반복문을 빠져나온다.
				switch(menu) {
					case 1:
						System.out.println("result="+num*num);
					case 2:
						System.out.println("result="+Math.sqrt(num));
					case 3:
						System.out.println("result="+Math.log(num));
				}
			}
		}
	}

//결과
(1) square
(2) square root
(3) log
원하는 메뉴(1~3)을 입력해주세요 (종료 0)
3
계산할 값을 입력해주세요. (계산종료 0, 전체종료:99) : 50
result=3.912023005428146
계산할 값을 입력해주세요. (계산종료 0, 전체종료:99) : 0
(1) square
(2) square root
(3) log
원하는 메뉴(1~3)을 입력해주세요 (종료 0)
0
프로그램을 종료합니다.

 

출처 : JAVA의 정석 - (남궁성지음)

    'JAVA/JAVA 기초' 카테고리의 다른 글
    • [JAVA 기초] String 배열화
    • [JAVA 기초] 배열 (선언, 생성, 길이, 초기화, 활용)
    • [JAVA 기초] 반복문(for문)
    • [JAVA 기초] 조건문(switch)
    큐범
    큐범

    티스토리툴바