본문 바로가기
Programming Languages/Java

Chapter 9. 반복

by 더 이프 2023. 1. 10.
728x90

목차

    1. 반복

    ■ 반복문

    • 조건에 따라 반복되는 것
    • 동일한 계산이나 명령을 순차적으로 반복해야할 경우에 사용
    • 지역 변수
      • 지역 변수는 지역 안에서만 사용 사능한 변수
      • 지역 변수의 지역 기준은 중괄호
    • 전역 변수
      • 전역 변수는 지역 변수 내에서도 사용 가능
      • 지역 변수 선언 전에 같은 변수명을 전역 변수에 사용하면 충돌이 일어남
      • 다른 지역 변수에는 같은 변수명을 사용해도 됨

    ■ For문

    • for문은 3가지 조건이 들어가며 조건이 충족되면 실행됨
    • 초기문은 한번에 여러개 선언 가능
    • for문은 조건에 해당하는 경우 실행하는 형태
      • for(변수 선언 및 초기화를 하는 초기문; 조건; 변화) {명령문};
    • forEach문은 배열의 값을 하나씩꺼내 변수에 대입하는 형태
      • for(변수 : 배열 or 리스트) {명령문};

    ■ While문

    • while문은 for문과 다르게 조건을 만족하면 무한반복함
    • while문을 연속하여 사용 시 변수를 초기화 시켜줘야 함
    • do ~ while문은 무조건 한 번은 실행 후에 반복할지를 결정
    • while문을 벗어나기 위해서는 break나 while문 내부에서 조건을 변경하는 식을 넣어야 함 

    ■ Break

    • break문은 break문이 있는 현재 위치를 감싸고 있는 반복문을 빠져나가기 위해 사용

    ■ Continue

    • continue문은 continue를 만나기 전까지 작업을 실행하다가 continue 이후의 작업을 무시하고 다음 반복 진행
    • break문과 다르게 반복의 실행을 종료하지 않음
    • while문에서는 continue를 만났을 때 조건식으로 이동
    • for문에서는 continue를 만났을 때 증감식으로 이동

     

    2. 예시

    ■ Loop1

    package j07_반복;
    
    public class Loop1 {
    
    	public static void main(String[] args) {
    		// for (초기문; 조건; 변화)
    		for (int i = 0; i < 10; i++) {
    			for (int j = 0; j < 10; j++) {
    				System.out.println(j);
    			}
    		}
    
    		int total = 0;
    
    		for (int i = 0; i < 100; i++) {
    			total += (i + 1);
    		}
    
    		System.out.println("총합 : " + total);
    	}
    }

    ■ Loop2

    package j07_반복;
    
    import java.util.Scanner;
    
    public class Loop2 {
    
    	public static void main(String[] args) {
    		Scanner scanner = new Scanner(System.in);
    		int startNumber = 0;
    		int endNumber = 0;
    		int total = 0;
    
    		System.out.print("시작 : ");
    		startNumber = scanner.nextInt();
    
    		System.out.print("끝 : ");
    		endNumber = scanner.nextInt();
    
    		for (int i = 0; i < (endNumber - startNumber + 1); i++) {
    			total += i + startNumber;
    			System.out.println(total);
    		}
    
    		System.out.println("총합 : " + total);
    	}
    }

    ■ Loop3

    package j07_반복;
    
    import java.util.Scanner;
    
    public class Loop3 {
    
    	public static void main(String[] args) {
    		Scanner scanner = new Scanner(System.in);
            
    		int count = 0;
    		int sum = 0;
    		int total = 0;
    
    		System.out.print("반복횟수 : ");
    		count = scanner.nextInt();
    
    		for (int i = 0; i < count; i++) {
    			int a = 0;
    			int b = 0;
    
    			System.out.println();
    			System.out.println((i + 1) + "번 반복");
    			System.out.print("a : ");
    			a = scanner.nextInt();
    			System.out.print("b : ");
    			b = scanner.nextInt();
    
    			sum = a + b;
    			System.out.println((i + 1) + "번 합 : " + sum);
    			total += sum;
    		}
    
    		System.out.println();
    		System.out.println("총합 : " + total);
    	}
    }

    ■ While1

    package j07_반복;
    
    public class While1 {
    
    	public static void main(String[] args) {
    
    		// 순서가 있는 경우 for문 위주(index)
    		for (int i = 0; i < 10; i++) {
    			System.out.println(i);
    		}
    		
    		// while문은 조건의 초기화가 필요함
    		int i = 0;
            
    		// 순서보다 조건이 중요할 경우 while문 위주
    		while (i < 10) {
    			System.out.println(i);
    
    			i++;
    		}
    	}
    }

    ■ While2

    package j07_반복;
    
    public class While2 {
    
    	public static void main(String[] args) {
    
    		int i = 0;
    
    		while (i < 10) {
    			int j = 0;
    
    			while (j < i + 1) {
    				System.out.print("*");
    				j++;
    			}
    
    			System.out.println();
    			i++;
    		}
    	}
    }

    ■ While3

    package j07_반복;
    
    import java.util.Scanner;
    
    public class While3 {
    
    	public static void main(String[] args) {
    		Scanner scanner = new Scanner(System.in);
            
    		// 문자열의 초기화값은 null임
    		String select = null;
    
    		while (true) {
    			System.out.print("x입력시 멈춤 : ");
    			select = scanner.nextLine();
                
    			// 문자열은 equals를 사용하여 같은지 확인
    			if (select.equals("x") || select.equals("X")) {
    				System.out.println("프로그램을 멈춥니다.");
    				break;
    			}
    
    			System.out.println("계속 실행!");
    		}
    
    		System.out.println("프로그램 종료됨.");
    	}
    }

    ■ Continue

    package j07_반복;
    
    import java.util.Iterator;
    
    public class Continue {
    
    	public static void main(String[] args) {
    
    		for (int i = 0; i < 10; i++) {
    			if (i % 2 != 0) {
    				// 다음 반복을 계속 진행시킴, 반복문으로 다시 돌아감
    				continue; 
    			}
    			System.out.println("i : " + i);
    		}
    
    		int i = 0;
    
    		while (i < 10) {
    			if (i % 2 != 0) {
    				i++;
    				continue;
    			}
    			System.out.println("i : " + i);
    			i++;
    		}
    	}
    }

    ■ Menu

    package j07_반복;
    
    import java.util.Scanner;
    
    public class Menu {
    
    	public static void main(String[] args) {
    		Scanner scanner = new Scanner(System.in);
    		String name = "김준일";
            
    		// charAt(i)는 문자열중 i번째 인덱스를 문자형으로 가져옴
    		System.out.println(name.charAt(0));
            
    		boolean loopFlag1 = true;
    
    		while (loopFlag1) {
    			char select = '\0';
    
    			System.out.println("========<< 식당 >>========");
    			System.out.println("1. 김밥천국");
    			System.out.println("2. 탄탄면");
    			System.out.println("3. 홍대개미");
    			System.out.println("4. 밥앤밥");
    			System.out.println("==========================");
    			System.out.println("q. 프로그램 종료");
    			System.out.println("==========================");
    			System.out.print("식당 번호 선택 : ");
                
    			// charAt(a)는 a번째 인덱스의 단어를 입력
    			select = scanner.next().charAt(0);
    
    			if (select == 'q' || select == 'Q') {
    				loopFlag1 = false;
    			} else if (select == '1') {
    				boolean loopFlag2 = true;
    
    				while (loopFlag2) {
    					System.out.println();
    					System.out.println("========<< 김밥천국 >>========");
    					System.out.println("1. 라면");
    					System.out.println("2. 돌솥비빔밥");
    					System.out.println("3. 오므라이스");
    					System.out.println("4. 김치볶음밥");
    					System.out.println("==============================");
    					System.out.println("b. 뒤로가기");
    					System.out.println("q. 프로그램 종료");
    					System.out.println("==============================");
    
    					System.out.print("메뉴 선택 : ");
    					select = scanner.next().charAt(0);
    
    					if (select == 'b' || select == 'B') {
    						// 메뉴 영역 종료
    						loopFlag2 = false;
    					} else if (select == 'q' || select == 'Q') {
    						// 식당, 메뉴 둘 다 종료
    						loopFlag1 = false;
    						loopFlag2 = false;
    					} else if (select == '1') {
    						System.out.println();
    						System.out.println("라면을 선택했습니다.");
    					} else if (select == '2') {
    						System.out.println();
    						System.out.println("돌솥비빔밥을 선택했습니다.");
    					} else if (select == '3') {
    						System.out.println();
    						System.out.println("오므라이스를 선택했습니다.");
    					} else if (select == '4') {
    						System.out.println();
    						System.out.println("김치볶음밥을 선택했습니다.");
    					} else {
    						System.out.println();
    						System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
    						System.out.println("사용할 수 없는 번호입니다.");
    						System.out.println("다시 입력하세요.");
    						System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
    					}
    					System.out.println();
    				}
    			} else if (select == '2') {
    				boolean loopFlag2 = true;
    
    				while (loopFlag2) {
    					System.out.println();
    					System.out.println("========<< 탄탄면 >>========");
    					System.out.println("1. 탄탄면");
    					System.out.println("2. 비빔탄탄면");
    					System.out.println("3. 마파탄탄면");
    					System.out.println("==============================");
    					System.out.println("b. 뒤로가기");
    					System.out.println("q. 프로그램 종료");
    					System.out.println("==============================");
    
    					System.out.print("메뉴 선택 : ");
    					select = scanner.next().charAt(0);
    
    					if (select == 'b' || select == 'B') {
    						loopFlag2 = false;
    					} else if (select == 'q' || select == 'Q') {
    						loopFlag1 = false;
    						loopFlag2 = false;
    					} else if (select == '1') {
    						System.out.println();
    						System.out.println("탄탄면을 선택했습니다.");
    					} else if (select == '2') {
    						System.out.println();
    						System.out.println("비빔탄탄면을 선택했습니다.");
    					} else if (select == '3') {
    						System.out.println();
    						System.out.println("마파탄탄면를 선택했습니다.");
    					} else {
    						System.out.println();
    						System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
    						System.out.println("사용할 수 없는 번호입니다.");
    						System.out.println("다시 입력하세요.");
    						System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
    					}
    				}
    			} else if (select == '3') {
    				boolean loopFlag2 = true;
    
    				while (loopFlag2) {
    					System.out.println();
    					System.out.println("========<< 홍대개미 >>========");
    					System.out.println("1. 대창 덮밥");
    					System.out.println("2. 스테이크 덮밥");
    					System.out.println("3. 연어 덮밥");
    					System.out.println("4. 불닭 덮밥");
    					System.out.println("==============================");
    					System.out.println("b. 뒤로가기");
    					System.out.println("q. 프로그램 종료");
    					System.out.println("==============================");
    
    					System.out.print("메뉴 선택 : ");
    					select = scanner.next().charAt(0);
    
    					if (select == 'b' || select == 'B') {
    						loopFlag2 = false;
    					} else if (select == 'q' || select == 'Q') {
    						loopFlag1 = false;
    						loopFlag2 = false;
    					} else if (select == '1') {
    						System.out.println();
    						System.out.println("대창 덮밥을 선택했습니다.");
    					} else if (select == '2') {
    						System.out.println();
    						System.out.println("스테이크 덮밥을 선택했습니다.");
    					} else if (select == '3') {
    						System.out.println();
    						System.out.println("연어 덮밥를 선택했습니다.");
    					} else if (select == '4') {
    						System.out.println();
    						System.out.println("불닭 덮밥을 선택했습니다.");
    					} else {
    						System.out.println();
    						System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
    						System.out.println("사용할 수 없는 번호입니다.");
    						System.out.println("다시 입력하세요.");
    						System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
    					}
    				}
    			} else if (select == '4') {
    				boolean loopFlag2 = true;
    
    				while (loopFlag2) {
    					System.out.println();
    					System.out.println("========<< 밥앤밥 >>========");
    					System.out.println("1. 소고기미역국");
    					System.out.println("2. 제육볶음");
    					System.out.println("3. 순두부 찌개");
    					System.out.println("4. 순두부 된장찌개");
    					System.out.println("==============================");
    					System.out.println("b. 뒤로가기");
    					System.out.println("q. 프로그램 종료");
    					System.out.println("==============================");
    
    					System.out.print("메뉴 선택 : ");
    					select = scanner.next().charAt(0);
    
    					if (select == 'b' || select == 'B') {
    						loopFlag2 = false;
    					} else if (select == 'q' || select == 'Q') {
    						loopFlag1 = false;
    						loopFlag2 = false;
    					} else if (select == '1') {
    						System.out.println();
    						System.out.println("소고기미역국을 선택했습니다.");
    					} else if (select == '2') {
    						System.out.println();
    						System.out.println("제육볶음을 선택했습니다.");
    					} else if (select == '3') {
    						System.out.println();
    						System.out.println("순두부 찌개를 선택했습니다.");
    					} else if (select == '4') {
    						System.out.println();
    						System.out.println("순두부 된장찌개을 선택했습니다.");
    					} else {
    						System.out.println();
    						System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
    						System.out.println("사용할 수 없는 번호입니다.");
    						System.out.println("다시 입력하세요.");
    						System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
    					}
    				}
    			} else {
    				System.out.println();
    				System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
    				System.out.println("사용할 수 없는 번호입니다.");
    				System.out.println("다시 입력하세요.");
    				System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
    			}
    			System.out.println();
    		}
    		System.out.println("프로그램 정상 종료!");
    	}
    }

    ■ Star

    package j07_반복;
    
    public class Star {
    
    	public static void main(String[] args) {
    
    		for (int i = 0; i < 10; i++) {
    			for (int j = 0; j < i + 1; j++) {
    				System.out.print("*");
    			}
    			System.out.println();
    		}
    
    		for (int i = 0; i < 10; i++) {
    			for (int j = 0; j < 10 - i; j++) {
    				System.out.print("*");
    			}
    			System.out.println();
    		}
    
    		for (int i = 0; i < 10; i++) {
    			for (int j = 0; j < 9 - i; j++) {
    				System.out.print(" ");
    			}
    
    			for (int j = 0; j < i + 1; j++) {
    				System.out.print("*");
    			}
    			System.out.println();
    		}
    
    		for (int i = 0; i < 10; i++) {
    			for (int j = 0; j < i; j++) {
    				System.out.print(" ");
    			}
    
    			for (int j = 0; j < 10 - i; j++) {
    				System.out.print("*");
    			}
    			System.out.println();
    		}
    
    		for (int i = 0; i < 10; i++) {
    			for (int j = 0; j < 9 - i; j++) {
    				System.out.print(" ");
    			}
    
    			for (int j = 0; j < i + 1; j++) {
    				System.out.print("*");
    			}
    
    			for (int j = 0; j < i; j++) {
    				System.out.print("*");
    			}
    			System.out.println();
    		}
    
    		for (int i = 0; i < 10; i++) {
    			for (int j = 0; j < i; j++) {
    				System.out.print(" ");
    			}
    
    			for (int j = 0; j < 10 - i; j++) {
    				System.out.print("*");
    			}
    
    			for (int j = 0; j < 9 - i; j++) {
    				System.out.print("*");
    			}
    
    			System.out.println();
    		}
    
    		for (int i = 0; i < 10; i++) {
    			if (i < 5) {
    				for (int j = 0; j < 9 - i; j++) {
    					System.out.print(" ");
    				}
    
    				for (int j = 0; j < i * 2 + 1; j++) {
    					System.out.print("*");
    				}
    			}
    			if (i > 4) {
    				for (int j = 0; j < i; j++) {
    					System.out.print(" ");
    				}
    				for (int j = 0; j < -2 * i + 19; j++) {
    					System.out.print("*");
    				}
    			}
    			System.out.println();
    		}
    	}
    }