본문 바로가기
📚 Stack/Java

[Java] 시뮬레이션 유형 풀이

by 개발한 너굴씨 2024. 6. 15.
728x90

 

1. 1차원 배열과 2차원 배열의 사용

 

1차원 배열

 

1차원 배열은 단순한 리스트나 배열의 형태로 데이터를 저장하고 처리할 때 사용함

  • 숫자의 리스트
  • 특정 값들의 카운트 배열
  • 간단한 순열이나 조합
int[] arr = new int[10];
arr[0] = 1;
arr[1] = 2;
// 배열 초기화와 사용

 

2차원 배열

2차원 배열은 행렬 형태로 데이터를 저장할 때 유용함

  • 게임 보드 (체스, 오목 등)
  • 그래프 표현 (인접 행렬)
  • 동적 계획법 테이블 (DP table)
int[][] matrix = new int[5][5];
matrix[0][0] = 1;
matrix[1][2] = 3;
// 2차원 배열 초기화와 사용

 

2. 문자열 처리 메소드

자바에서는 문자열을 다룰 때 String 클래스의 다양한 메소드를 사용할 수 있음

String str = "Hello, World!";
char ch = str.charAt(0); // 'H'
int length = str.length(); // 13
String substr = str.substring(0, 5); // "Hello"
boolean contains = str.contains("World"); // true
String replaced = str.replace("World", "Java"); // "Hello, Java!"
String[] parts = str.split(", "); // ["Hello", "World!"]

 

 

3. 예외 처리

구현 문제에서는 예상치 못한 입력이나 예외 상황을 잘 처리하는 것이 중요 예외 처리를 할 때는 try-catch 블록을 사용

public class ExceptionHandlingExample {
    public static void main(String[] args) {
        try {
            // 예외가 발생할 가능성이 있는 코드
            int num = Integer.parseInt("123a"); // NumberFormatException 발생
        } catch (NumberFormatException e) {
            // NumberFormatException이 발생했을 때 처리할 코드
            System.out.println("잘못된 숫자 형식입니다.");
        } finally {
            // 예외 발생 여부와 상관없이 항상 실행되는 코드
            System.out.println("예외 처리를 마쳤습니다.");
        }

        // 여러 예외를 처리하는 경우
        try {
            int[] arr = new int[5];
            System.out.println(arr[10]); // ArrayIndexOutOfBoundsException 발생
        } catch (NumberFormatException e) {
            // NumberFormatException 처리
            System.out.println("잘못된 숫자 형식입니다.");
        } catch (ArrayIndexOutOfBoundsException e) {
            // ArrayIndexOutOfBoundsException 처리
            System.out.println("배열 인덱스가 범위를 벗어났습니다.");
        } catch (Exception e) {
            // 모든 예외의 부모 클래스인 Exception으로 나머지 모든 예외 처리
            System.out.println("알 수 없는 예외가 발생했습니다.");
        } finally {
            System.out.println("배열 예외 처리를 마쳤습니다.");
        }
    }
}

 

 

4. 입출력 처리 

BufferedReader와 BufferedWriter 사용 예제

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.IOException;

public class Main {
    public static void main(String[] args) {
        // BufferedReader와 BufferedWriter를 사용하기 위해 try-with-resources 문법 사용
        try (
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out))
        ) {
            // 한 줄을 입력 받음
            String input = br.readLine();
            
            // 입력 받은 문자열을 출력
            bw.write("입력 받은 문자열: " + input);
            bw.newLine(); // 줄 바꿈 추가
            bw.flush(); // 버퍼를 비우고 실제로 출력

            // 예제: 여러 줄 입력을 받아서 처리하는 경우
            int numberOfLines = Integer.parseInt(br.readLine()); // 첫 줄에 입력될 숫자(라인 수)
            for (int i = 0; i < numberOfLines; i++) {
                String line = br.readLine();
                bw.write("라인 " + (i + 1) + ": " + line);
                bw.newLine();
            }
            bw.flush(); // 마지막에 버퍼를 비워 출력
        } catch (IOException e) {
            e.printStackTrace(); // 예외 발생 시 스택 트레이스 출력
        }
    }
}

 

 

 

 

728x90

댓글