조건을 먼저 검사한 후, 조건이 true인 동안 계속 반복하는 구조.
package lesson02;
public class Ex09_While1 {
public static void main(String[] args) {
int i = 1;
while (i<=5) {
System.out.println(i);
i++;
}
}
}
1
2
3
4
5
package lesson02;
import java.util.Scanner;
public class Ex10_While2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input = "";
while(!input.equals("exit")){
System.out.print("문장을 입력하세요 (종료: exit): ");
input = sc.nextLine();
System.out.println("입력한 내용: " + input);
}
System.out.println("프로그램을 종료합니다.");
sc.close();
}
}
문장을 입력하세요 (종료: exit): hello
입력한 내용: hello
문장을 입력하세요 (종료: exit): exit
입력한 내용: exit
프로그램을 종료합니다.
일단 한 번 실행하고, 그 다음에 조건을 검사하여 반복 여부를 결정하는 반복문. (조건이 false여도 최소 한 번은 무조건 실행)
package lesson02;
import java.util.Scanner;
public class Ex11_DoWhile {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input = "";
do {
System.out.print("문장을 입력하세요 (종료: exit): ");
input = sc.nextLine();
System.out.println("입력한 내용: " + input);
} while (!input.equals("exit"));
System.out.println("프로그램을 종료합니다.");
sc.close();
}
}
결과는 위 Ex10_While2 클래스와 동일.
반복 횟수가 정해져 있는 경우에 사용하는 반복문.
package lesson02;
public class Ex12_For1 {
public static void main(String[] args) {
for(int i=1; i<=5; i++){
System.out.println("i = " + i);
}
}
}
i = 1
i = 2
i = 3
i = 4
i = 5
package lesson02;
import java.util.Random;
import java.util.Scanner;
public class Ex13_For2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Random rand = new Random();
System.out.print("주사위를 몇 번 던질까요? ");
int count = sc.nextInt();
for (int i = 1; i <= count; i++) {
int dice = rand.nextInt(6) + 1; // 1~6 사이의 숫자 생성
System.out.println(i + "번째 주사위: 🎲 " + dice);
}
sc.close();
}
}
주사위를 몇 번 던질까요? 3
1번째 주사위: 🎲 6
2번째 주사위: 🎲 2
3번째 주사위: 🎲 6
자바의 java.util.Random 클래스
-> 무작위(랜덤) 숫자를 생성.
Random 객체는 한 번만 생성해서 계속 사용하는 게 좋음.
nextInt() 정수(int) 전체 범위 중 랜덤 생성 -2,147,483,648 ~ 2,147,483,647
nextInt(n) 0 이상 n 미만의 정수 중 랜덤 생성 nextInt(6) → 0~5
nextDouble() 0.0 이상 1.0 미만의 실수 생성 예: 0.2364
nextBoolean() true 또는 false 중 무작위로 하나 반환 예: true
break : 자바에서 반복문(for, while, do-while) 또는 switch문을 즉시 종료.
package lesson02;
import java.util.Scanner;
public class Ex14_Break {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(true){
System.out.print("문장을 입력하세요 (종료하려면 exit 입력): ");
String input = sc.nextLine();
if(input.equals("exit")){
System.out.println("프로그램을 종료합니다.");
break;
}
System.out.println("입력한 문장: " + input);
}
sc.close();
}
}
문장을 입력하세요 (종료하려면 exit 입력): hello~
입력한 문장: hello~
문장을 입력하세요 (종료하려면 exit 입력): exit
프로그램을 종료합니다.
💥 중첩 반복문에서는 break를 쓰면 가장 가까운 바깥 반복문 한 개만 종료된다.
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (j == 2) break; // 안쪽 반복문만 멈춤
System.out.println("i=" + i + ", j=" + j);
}
}
💥 라벨(label) -> 반복문 앞에 이름을 붙여서, break가 어느 반복문을 종료할지 명확하게 지정할 수 있게 한다.
outer: for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (j == 2) break outer; // 바깥 반복문까지 종료!
System.out.println("i=" + i + ", j=" + j);
}
}
현재 반복문의 나머지 코드를 건너뛰고, 다음 반복을 바로 시작하도록 만듬.
package lesson02;
public class Ex15_Continue {
public static void main(String[] args) {
for(int i = 1; i<=10; i++){
if(i%2==0){
continue;
}
System.out.println("홀수: "+i);
}
}
}
홀수: 1
홀수: 3
홀수: 5
홀수: 7
홀수: 9
자바의 향상된 for문(enhanced for loop)
-> 배열이나 컬렉션(List, Set 등)의 모든 요소를 순차적으로 한 번씩 처리할 때 사용하는 간결한 반복문.
인덱스를 따로 신경 쓰지 않고도 전체 요소를 꺼내 사용할 수 있다.
: 왼쪽 배열이나 컬렉션에서 꺼낸 값이 저장될 변수: 오른쪽 배열 또는 컬렉션 자체package lesson02;
public class Ex16_Enhanced {
public static void main(String[] args) {
String[] names = {"김사과", "오렌지", "이메론", "반하나"};
for(int i = 0; i<names.length; i++){
System.out.println(names[i]);
}
for(String name: names){
System.out.println("이름: "+ name);
}
}
}
김사과
오렌지
이메론
반하나
이름: 김사과
이름: 오렌지
이름: 이메론
이름: 반하나
package lesson02;
import java.util.Scanner;
public class Ex17_Coord {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("맵의 행 수를 입력하세요: ");
int rows = sc.nextInt();
System.out.print("맵의 열 수를 입력하세요: ");
int cols = sc.nextInt();
System.out.println("[맵 좌표 출력]");
for (int i = 0; i < rows; i++){
for(int j = 0; j<cols; j++){
System.out.print("(" + i + "," + j + ")");
}
System.out.println();
}
sc.close();
}
}
맵의 행 수를 입력하세요: 3
맵의 열 수를 입력하세요: 2
[맵 좌표 출력]
(0,0)(0,1)
(1,0)(1,1)
(2,0)(2,1)
package lesson02;
import java.util.Random;
import java.util.Scanner;
public class Ex18_Treasure {
public static void main(String[] args) {
final int SIZE = 5;
char[][] map = new char[SIZE][SIZE];
// 초기 맵은 모두 '-'로 표시
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
map[i][j] = '-';
}
}
// 보물 위치 설정
Random rand = new Random();
int treasureRow = rand.nextInt(SIZE);
int treasureCol = rand.nextInt(SIZE);
Scanner sc = new Scanner(System.in);
boolean found = false;
while (!found) {
// 현재 맵 출력
System.out.println("\n[맵 상태]");
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
System.out.print(map[i][j] + " ");
}
System.out.println();
}
// 사용자 입력
System.out.print("\n행 번호 (0~4): ");
int row = sc.nextInt();
System.out.print("열 번호 (0~4): ");
int col = sc.nextInt();
// 입력 유효성 검사
if (row < 0 || row >= SIZE || col < 0 || col >= SIZE) {
System.out.println("⚠️ 유효한 좌표를 입력하세요.");
continue;
}
// 보물 발견 여부 확인
if (row == treasureRow && col == treasureCol) {
map[row][col] = '💎';
found = true;
System.out.println("\n🎉 축하합니다! 보물을 찾았습니다!");
} else {
if (map[row][col] == '❌') {
System.out.println("😅 이미 시도한 위치입니다.");
} else {
map[row][col] = '❌';
System.out.println("🙁 여긴 아니에요. 다시 시도하세요.");
}
}
}
// 최종 맵 출력
System.out.println("\n[최종 맵]");
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
System.out.print(map[i][j] + " ");
}
System.out.println();
}
sc.close();
}
}