[Java] 코딩 테스트를 위한 자바 기초 문법 정리

최윤서·2025년 6월 1일

Java

목록 보기
1/2
post-thumbnail

✏️ 문제 풀면서 정리한 자바 문법들

1. 입력

1. 문자(char) 입력

Scanner sc = new Scanner(System.in);
char ch = sc.next().charAt(0); // 문자열 중 첫 글자만 가져옴
/*자바 Scanner은 String 타입으로만 입력을 받기 때문에 char타입을 입력받는 기능이 없음. 따라서 charAt(0)을 사용*/

2. 문자열(String) 입력

Scanner sc = new Scanner(System.in);
String str = sc.nextLine(); // 한 줄 전체 입력

3. 정수(int) 입력

Scanner sc = new Scanner(System.in);
int num = sc.nextInt(); 

4. 문자열 "apple"

Scanner sc = new Scanner(System.in);
String str = sc.nextLine();

5. 문자열 배열 {"apple", "banana"}

Scanner sc = new Scanner(System.in);
String[] strArr = sc.nextLine().split(" "); // 공백 (" ") 기준

6. n개의 문자열을 한 줄씩 입력받는 경우

Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
sc.nextLine(); // 버퍼 비우기

String[] strArr = new String[n];
for (int i = 0; i < n; i++) {
    strArr[i] = sc.nextLine();
}

7. 문자형 배열 {'a', 'b'}

8. 정수 배열

9. 정수형 리스트(ArrayList) 입력

Scanner sc = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<>(); // 선언

for (int i = 0; i < n; i++) {
    list.add(scanner.nextInt());
}

2. 초기화

1. 정수형 리스트

ArrayList<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3)); // [1, 2, 3]

3. 길이 구하기

종류내용예시
length배열의 길이를 구할 때int[] arr = new int[5]; arr.length
length()문자열의 길이를 구할 때String s = "hello"; s.length()
size()List, Set 등의 크기 구할 때ArrayList<Integer> list; list.size()

4. Set이란?

중복을 허용하지 않는 자료구조 (순서도 보장하지 않음)

static Set<Character> set = new HashSet<>();         // 선언 (문자형 Set)
set.add();                                           // 추가
set.remove();                                        // 삭제

5. Map이란?

Map은 Key -> Value 형태로 데이터를 저장하는 자료구조.

(예: 학생번호 -> 이름, 상품ID -> 가격)
Map<String, Integer> map = new HashMap<>(); // String -> Integer

        // 값 추가
        map.put("apple", 3);
        map.put("banana", 5);

        // 값 가져오기
        System.out.println(map.get("apple")); // 출력: 3

        // 키 존재 확인
        System.out.println(map.containsKey("banana")); // 출력: true

        // 값 삭제
        map.remove("apple");
        
        // 반복
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            System.out.println(entry.getKey() + entry.getValue());
        }

6. 값 추가/삭제 방법

1. ArrayList

ArrayList<Integer> list = new ArrayList<>();

// 값 추가
list.add(1);  // index 0
list.add(3);  // index 1

// 원하는 위치(index 1)에 2 추가
list.add(1, 2);  // [1, 2, 3]

// 값 삭제 
list.remove(list.size() - 1); // ()안에 삭제할 index 번호를 넣어주면 됨.
list.remove(1); // 1번째 index값 삭제

2. int[]

int[] 배열은 고정 크기이기 때문에 ArrayList처럼 원하는 자리에 값을 추가하거나 삭제할 수 없다.

// 연구소
import java.util.*;

public class BJ14502 {
    static int n, m;
    static int[][] graph;
    static int maxSafeZone = 0;
    static boolean[][] visited = {{}}; // 방문 배열
    static ArrayList<Integer> virusList = new ArrayList<>(); 
    // static Queue<Integer> queue = new LinkedList<>(); // 정수 Queue.
    // 동서남북
    static int[] dx = {0, 0, 1, -1};  
    static int[] dy = {1, -1, 0, 0};

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // 입력
        n = scanner.nextInt();
        m = scanner.nextInt();
        
        graph = new int[n][m];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                graph[i][j] = scanner.nextInt();
            }
        } 

        // 방문 배열 초기화
        visited = new boolean[n][m];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                visited[i][j] = false;
            }
        }

        createWalls(0);
        System.out.println(maxSafeZone);
        
    }

    public static void createWalls(int wall) {
        int[][] newGraph = {{}};
        if (wall == 3) {
            // visited 초기화
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    visited[i][j] = false;
                }
            }

            // 바이러스 퍼뜨린 후
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    if (graph[i][j] == 2) {
                        newGraph = new int[n][m];
                        newGraph = spreadVirus(i, j);
                    }   
                }
            }

            // 그래프 출력
            System.out.println("newGraph 출력");
            for (int i = 0; i < n; i++) {
                for (int j = 0; j <m; j++) {
                    System.out.print(newGraph[i][j] + " ");
                }
                System.out.println();
            }  

            // 안전 영역 새기
            int num = calSafeZone(newGraph);
            System.out.println("안전영역 출력: " + num);
            if (num > maxSafeZone) maxSafeZone = num; // 최댓값 갱신
            return;
        }

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (graph[i][j] == 0) {
                    graph[i][j] = 1;
                    createWalls(wall + 1);
                    graph[i][j] = 0;
                }
            }
        }
    }

    // 바이러스 확산 함수 -> bfs
    public static int[][] spreadVirus(int startX, int startY) {
        // queue 초기화
        Queue<Integer> queue = new LinkedList<>(); // 정수 Queue.
        
        // graph 복사
        int[][] tempGraph = new int[n][m];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                tempGraph[i][j] = graph[i][j];
            }
        }

        System.out.println("tempGraph 출력");
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                System.out.print(tempGraph[i][j] + " ");
            }
            System.out.println();
        }

        // 방문 처리
        visited[startX][startY] = true;
        queue.add(startX);
        queue.add(startY);

        while (!queue.isEmpty()) { // queue가 비지 않을 때까지
            int x = queue.poll();
            int y = queue.poll();
            // 동서남북 보기
            for (int i = 0; i < 4; i++) {
                int nx = x + dx[i];
                int ny = y + dy[i];
                // 범위 && 방문하지 않음 && 0이면
                if (((0 <= nx && nx < n) && (0 <= ny && ny < m)) && visited[nx][ny] == false && tempGraph[nx][ny] == 0) {
                    queue.add(nx);
                    queue.add(ny);
                    tempGraph[nx][ny] = 2; // virus 퍼뜨리기.
                }
            }
        }
        
        return tempGraph;
        
    }

    // 안전영역 새는 함수
    public static int calSafeZone(int[][] newGraph) {
        int maxValue = 0; // 최소 안전 영역은 0.
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (newGraph[i][j] == 0) {
                    System.out.println("!!!");
                    maxValue += 1;
                }
            }
        }
        System.out.println(maxValue);
        return maxValue;
    }
}

0개의 댓글