본문 바로가기
학습/JAVA

4. 반복문(for문, while문, do-while문

by Elfen Lied 2022. 9. 30.
반응형

- for 문

public class ForExam {

	public static void main(String[] args) {
		// (초기화식; 조건식; 증감식)
		// 조건식이 true이면 중괄호 블럭 실행
		// 순서: 초기화식 - 반복구간[조건식 - 실행문 - 증감식]
		for(int i=0; i<5; i++) {
			System.out.println("Hello " + i);
		}
	}
}

값
Hello 0
Hello 1
Hello 2
Hello 3
Hello 4

 

 

 

- 중첩된 for문

- 구구단(for문)

public class GugudanExam {

	public static void main(String[] args) {
		
		for(int m = 2; m<=9; m++) {
			for(int i=1; i<=9; i++) {
				System.out.println(m + "x" + i + "=" + m*i);
			}
			System.out.println();
		}
	}
}

 

 

- 별찍기

public class StarExam {

	public static void main(String[] args) {
		for(int i=1; i<=5; i++) {
			for(int j=1; j<=i; j++) {
				System.out.print("*");
			}
			System.out.println();
		}
	}
}

 

 

 

- while문

public class WhileExam {
	
	public static void main(String[] args) {
		
		int i = 0;
		while(i<4) {
			System.out.println("hi " + i);
			i++;
		}
	}
}

값
hi 0
hi 1
hi 2
hi 3

 

- while문 조건식 제어

while문은 true의 조건을 주면 무한 반복한다.

scanner로 제어 하기

public class WhileExam4 {
	
	public static void main(String[] args) {
		
		Scanner scanner = new Scanner(System.in);
		boolean run = true;
		
		while(run) {
			System.out.println("Hey");
			System.out.print(">>명령어를 입력하라 ");
			String exit = scanner.nextLine();
			if(exit.equals("exit")) {
				run = false;
			}
		}
		System.out.println("종료");
	}
}

while(run) 실행되고 hey를 찍은 뒤, scanner 명령어에서 대기

이때 exit를 입력하면 if문에서 조건 확인후 run 변수에 false가 할당되어 while문 종료.

 

 

- do while문

  • while문과 동일하지만
  • 무조건 중괄호 {}블록을 한 번 실행한 후, 조건 검사해 반복 결정
public class Exam03 {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		System.out.println("메세지 입력");
		System.out.println("프로그램 q 입력시 종료");
		
		String inputString = null;
		
		do {
			System.out.println(">>");
			inputString = scanner.nextLine();
			System.out.println("입력한 값 : " + inputString);
		} while(!inputString.equals("q"));
		
		System.out.println("종료");
	}
}

 

 

 

- break문

public class BreakExample {
	
	public static void main(String[] args) {
		
		while(true) {
			int num = (int)(Math.random() * 6) + 1;
			System.out.println("생성된 주사위 눈 : " + num);
			if(num==6) break;
		}
		System.out.println("종료");
	}
}

 

 

 

- 중첩된 반복문에서 외부 반복문 탈출

public class BreakOutterExample {

	public static void main(String[] args) {
		Outter : for(char upper='A'; upper <= 'Z'; upper++) {
			for(char lower='a'; lower<='z'; lower++) {
				System.out.println(upper + "_" + lower);
				if(lower=='g') break Outter;
			}
		}
	}
}

break만 붙으면 전체가 반복되지만, (A-g ~ Z-g)

break 뒤에 Outter을 붙이면 전체 반복이 탈출된다. (A-g)

(Outter 이름은 임의로 지을수 있음)

 

 

 

- continue

public class ContinueExample {

	public static void main(String[] args) {
		for (int i=1; i<=10; i++) {
			if(i%2==0) continue;
			System.out.println(i);
		}
	}
}

값
2
4
6
8
10

 

반응형

'학습 > JAVA' 카테고리의 다른 글

5. 열거 타입  (0) 2022.10.05
5. 참조 타입  (0) 2022.10.04
4. 조건문(if문, switch문)  (0) 2022.09.29
3. 연산자(3)  (0) 2022.09.29
3. 연산자(2)  (0) 2022.09.28

댓글