본문 바로가기
Programming Language/Java

[국비] Java 내용정리 Day05

by tpleehan 2021. 10. 29.

반복문 중첩(loop nesting) 

  • 외부 반복문 내부에 내부 반복문이 존재하는 형태를 반복문 중첩이라 한다.
    반복문 자체를 반복시켜야 할 경우에 중첩을 사용한다.
  • 내부 반복문이 종료가 되어도, 외부 반복문이 끝나지 않으면 내부 반복문은 외부 반복문의 제어변수의 크기 및 범위까지 계속해서 반복 실행하게 된다.
public class LoopNesting {
	public static void main(String[] args) {
		
		for(int dan = 2; dan  <= 9; dan++) {
			System.out.println("구구단 " + dan + "단");
			System.out.println("--------------------");
			
			for(int hang = 1; hang <= 9; hang++) {
				System.out.printf("%d x %d = %d\\n", dan, hang, dan * hang);
			}
			
			System.out.println("--------------------");
			
		}
	}
}

LoopNesting Quiz01

문제1)
구구단을 다음과 같이 가로로 출력한다.

예시)
2단: 2x1=2 2x2=4 2x3=6 .....
3단: 3x1=2 3x2=4 3x3=6 .....
4단: 4x1=2 4x2=4 4x3=6 .....

문제2)
구구단을 다음과 같이 세로로 출력한다.
각 단의 간격은 탭 하나로 고정한다.

예시)
2단        3단        4단    ...
2x1=2    3x1=3    4x1=4    ...
2x2=4    3x2=6    4x2=8    ...
2x3=6    3x3=9    4x3=12    ...
. . . . . . . . .
2x9=18    3x9=27    4x9=36    ...
public class LoopNestingQuiz01 {
	public static void main(String[] args) {

		//Q1.
		for(int dan = 2; dan <= 9; dan++) {
			System.out.print(dan + "단: ");
			for(int hang = 1; hang <= 9; hang++) {
				System.out.printf("%dx%d=%d ", dan, hang, dan * hang);
			}
			System.out.println();
		}
		System.out.println("\\n---------------------------------------\\n");
		
		//Q2.
//		for(int dan = 2; dan <= 9; dan++) {
//			System.out.printf("%d단\\t", dan);
//		}
//		System.out.println();
//		for(int i = 1; i <= 9; i++) {
//			for(int j = 2; j <= 9; j++) {
//				System.out.printf("%dx%d=%d\\t ", j, i, j * i);
//			}
//			System.out.println();
//		}
		
		for(int hang = 0 ; hang <= 9; hang++) {
			for(int dan = 2; dan <= 9; dan++) {
				if(hang == 0) {
					System.out.print(dan + "단\\t");
				} else {
					System.out.printf("%dx%d=%d\\t", dan, hang, dan * hang);
				}
			}
			System.out.println();
		}		
	}
}​

LoopNesting Quiz02

문제)
정수를 하나 입력 받아서 해당 숫자까지의 모든 소수를 가로로 출력하고, 그 소수들의 개수를 구하는 로직을 작성한다.

예시)
입력받은 수 -> 12
소수: 2 3 5 7 11
소수의 개수: 5개
import java.util.Scanner;

public class LoopNesting2 {
	public static void main(String[] args) {
    
		Scanner sc = new Scanner(System.in);
		System.out.print("입력: ");
		int num = sc.nextInt();
		int cnt = 0; //소수의 개수를 세어 줄 변수
		
		for(int i = 1; i <= num; i++) {
			int count = 0; //소수 판별을 위해서 약수의 개수를 세어 줄 변수.
			for(int j = 1; j <= i; j++) {
				if(i % j == 0) {
					count++;
				}
			}
			if(count == 2) {
				cnt++;
				System.out.print(i + " ");
			}
		}
		
		System.out.println("\\n소수의 개수: " + cnt + "개");
		sc.close();
	}
}​

탈출문 break

  • 내부 반복문에 포함된 break로 바깥쪽 반복문까지 한번에 종료시키고 싶다면 바깥쪽 반복문에 label을 붙인다. 그리고 break 선언 시 label을 함께 선언한다.
public class BreakExample1 {
	public static void main(String[] args) {
		
		for(int i=1; i<=10; i++) {
			if(i > 7) {
				break;
			}
			System.out.print(i + " ");
		}
		System.out.println("\\n반복문 종료");
		
		System.out.println("----------------------------------------");
		
		outer: for(int i=0; i<=2; i++) {
			for(int j=0; j<=1; j++) {
				if(i == j) {
					break outer;
				}
				System.out.println(i + "-" + j);
				
			}
		}		
	}
}

 무한 루프

  • 반복 횟수를 정하지 않고 무한하게 반복문을 실행하는 구조
  • 처음 반복문을 구성할 때, 개발자가 사전에 정확한 반복 횟수를 파악하지 못 한다면, 무한루프를 먼저 구성해 두고 특정 조건을 통해 종료할 수 있도록 코드를 설계한다.
  • 일반적으로 정확한 반복 횟수를 알고 있으면 for문을 사용하고, 정확한 반복 횟수를 모른다면 while을 통한 무한 루프를 형성하여 사용한다. 
while(true), for(;;)
import java.util.Scanner;

public class BreakExample2 {
	public static void main(String[] args) {
		
		int i = 1;
		
		while(true) {
			if(i > 5) {
				break;
			}
			System.out.println("안녕하세요.");
			i++;
		}
		
		System.out.println("----------------------------------");
		
		Scanner sc = new Scanner(System.in);
		
		while(true) {
			System.out.println("15 x 6 = ???");
			System.out.println("정답을 모를경우 숫자 0을 입력하면 종료됩니다.");
			System.out.print("> ");
			int answer = sc.nextInt();
			
			if(answer == 90) {
				System.out.println("정답입니다.");
				break;
			} else if (answer == 0) {
				System.out.println("정답은 90 입니다.");
				break;
			} else {
				System.out.println("오답입니다.");
			}
			
		}
		
		sc.close();		
	}
}

Break Quiz01

문제)
1. 2가지의 정수를 1~100사이의 난수를 발생시켜서 지속적으로 문제를 출제한 후 정답을 입력 받는다.
    사용자가 0을 입력하면 반복문을 종료시킨다.
2. 종료 이후에 정답 횟수와 오답 횟수를 각각 출력한다.
import java.util.Scanner;

public class BreakQuiz01 {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int cCount = 0;
		int iCount = 0;

		System.out.println("*** 연산 퀴즈 ***");
		System.out.println("종료하시려면 0을 입력하세요.");
		
		while(true) {
			int rn1 = (int) ((Math.random() * 100) + 1);
			int rn2 = (int) ((Math.random() * 100) + 1);
			int num = (int) (Math.random()*2);
			
			int correct;
			if (num == 0) {
				System.out.println(rn1 + " + " + rn2 + " = " + "???");
				correct = rn1 + rn2;
			} else {
				System.out.println(rn1 + " - " + rn2 + " = " + "???");
				correct = rn1 - rn2;
			}
			
			System.out.print("> ");
			int answer = sc.nextInt();
				
			if(answer == correct) {
				System.out.println("정답입니다.");
				cCount++;
				
			} else if (answer == 0) {
				System.out.println("종료합니다.");
				break;
				
			} else {
				System.out.println("오답입니다.");
				iCount++;
				
			}
			
		}
		System.out.println("--------------------------------------");
		System.out.println("정답 횟수: " + cCount + "회");
		System.out.println("오답 횟수: " + iCount + "회");
		
		sc.close();		
	}
}​

Break Quiz02

문제)
# UP&DOWN 게임 제작 #
1. 기준이 되는 수는 난수 범위 1~100까지로 지정한다.
2. 사용자에게 정답을 입력받아, 기준이 되는 수보다 작은 수를 입력하면 UP, 큰 수를 입력하면 DOWN이라고 출력해서 정답에 근접할 수 있도록 유도한다.
3. 승리 조건 횟수는 7회로 제한한다. 7회가 넘어가도 정답은 계속 맞출 수 있도록 작성한다.
    정답을 맞췄다면, 반복문 종료와 함께 승리/패배 여부를 알려준다.
import java.util.Scanner;

public class BreakQuiz2 {
	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);
		System.out.println("*** UP & DOWN GAME ***");
		System.out.println("# 1부터 100까지의 정수 중 숫자를 선택하세요.");
		
		int secret = (int) ((Math.random() * 100) + 1);
		int count = 0;
		
		while(true) {
			System.out.print("> ");
			int answer = sc.nextInt();
			
			if (answer > 100 || answer < 1) {
				System.out.println("입력을 제대로 해주세요.");
				continue;
			}
			
			count++;
			
			if (answer > secret) {
				System.out.println("Down");
			} else if (answer < secret) {
				System.out.println("Up");
			} else {
				System.out.println("정답입니다.");
				break;
			}
			
			if(count < 7) {
				System.out.println("정답 기회 " + (7-count) + "번 남았습니다.");
			} else {
				System.out.println("정답 기회를 모두 소진했습니다.");
				System.out.println("정답을 맞춰주시기 바랍니다.");
			}
			
		}
		
		System.out.println(count + "번 만에 맞췄습니다.");
		
		if(count <= 7) {
			System.out.println("승리했습니다.");
		} else {
			System.out.println("패배했습니다.");
		}
		
		sc.close();		
	}
}​

탈출문 continue

  • continue문은 for문이나 while문에서 사용되며 반복문이 실행 중 continue를 만나는 순간 for문의 경우 증감식, while문의 경우 조건식으로 이동한다.
  • continue는 break와 달리 반복문을 종료하지 않고 계속 수행한다.
  • 조건부로 특정 반복회차를 건너뛸 때 사용한다.
import java.util.Scanner;

public class ContinueExample {

	public static void main(String[] args) {
		
		for(int i = 1; i <= 10; i++) {
			if(i == 5) {
				continue;
			}
			System.out.print(i + " ");
		}
		System.out.println("\\n반복문 종료");
		
		System.out.println("\\n--------------------------------");
		
		Scanner sc = new Scanner(System.in);
		System.out.println("정수를 입력하세요. ");
		
		while(true) {
			System.out.print("> ");
			int answer = sc.nextInt();
			
			if(answer == 1) {
				break;
		
			} else if (answer == 0) {
				System.out.println("다른 정수를 입력하세요.");
				continue;
			
			} else {
				System.out.println("입력한 정수와의 나눗셈 결과: " + (100 / answer));
			}
			
		}
		
		sc.close();
		
	}

}

'Programming Language > Java' 카테고리의 다른 글

[국비] Java 내용정리 Day07  (0) 2021.11.03
[국비] Java 내용정리 Day06  (0) 2021.11.01
[국비] Java 내용정리 Day04  (0) 2021.10.29
[국비] Java 내용정리 Day03  (0) 2021.10.28
[국비] Java 내용정리 Day02  (0) 2021.10.26

댓글