본문 바로가기

알고리즘

자바 입/출력 처리

1. java.util.Scanner

- 파일, 입력 스트림 등에서 데이터를 읽어 구분자로 토큰화하고 다양한 타입으로 형변환하여 리턴해주는 클래스

ex) Scanner(File source)

ex) Scanner(InputStream source)

ex) Scanner(String source)

- 입력 스트림을 다루는 방법을 몰라도 손쉽게 입력 처리 가능

- 데이터 형변환으로 인한 편리함

- 대량의 데이터 처리 시 수행시간이 비효율적임

-> BufferedReader 사용하여 해결

-> BufferedReader는 다양한 타입의 형변환을 안해주므로 유저가 직접 구현해야 함

 

Scanner의 주요 메소드

- nextInt(): int 타입 반환, 유효 문자열 후 White space 문자를 만나면 처리

- nextDouble(): double 타입 반환, 유효 문자열 후 White space 문자를 만나면 처리

- next(): 문자열 반환, 유효 문자열 후 White space문자를 만나면 처리

- nextLine(): 문자열 반환, 개행(Enter)문자를 만나면 처리, next()와 달리 문자열 안에 띄어쓰기 가능(space, tab 포함 가능)

import java.util.Scanner;

public class ScannerTest {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.print("int input = ");
		int no = sc.nextInt();
		System.out.println("no = " + no);
		System.out.print("String input = ");
//		String msg = sc.next();
		sc.nextLine(); //이전 입력으로 인해 남아있는 찌꺼기 무시하기 위해
		String msg = sc.nextLine();

		System.out.println("msg =  " + msg);
	}
}

 

2. java.io.BufferedReader

- Reader: 입력스트림, char 단위 입력

- 필터 스트림 유형

- 파라미터는 Reader type -> new InputStreamReader(System.in) -> 다형성

- 줄(line) 단위로 문자열 처리 기능 제공 -> readLine()

- 대량의 데이터 처리 시 수행시간이 효율적임

public class BufferedReaderScannerTest {
	public static void main(String[] args) throws NumberFormatException, IOException {
		System.setIn(new FileInputStream("inputTc.txt"));
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

		long start = System.nanoTime();

		int TC = Integer.parseInt(in.readLine());
		for (int tc = 1; tc <= TC; tc++) {

			int sum = 0;
			int n = Integer.parseInt(in.readLine());
			for (int i = 0; i < n; i++) {
				StringTokenizer st = new StringTokenizer(in.readLine(), " ");
				for (int j = 0; j < n; j++) {
					sum += Integer.parseInt(st.nextToken());
				}
			}
			System.out.println("#" + tc + " " + sum);
		}

		long end = System.nanoTime();
		System.out.println((end - start) / 1_000_000_000.0 + "s");
	}
}

 

 

3. java.lang.StringBuilder

- 문자열의 조작을 지원하는 클래스

- 자바에서 상수로 취급되는 문자열을 조작 시마다 새로운 문자열이 생성되는 것을 방지해줌

- append(String s): StringBuilder 뒤에 값을 붙임

- delete(int start, int end): 특정 인덱스부터 인덱스까지 삭제

- insert(int offset, any primitive of a char[]): 문자를 삽입함

- replace(int start, int end, String s): 일부를 String 객체로 치환

- reverse(): 순서를 뒤집음

- setCharAt(int index, char ch): 주어진 문자를 치환

- indexOf(String s): 값이 어느 인덱스에 들어있는지 확인

- subString(int start, int end): start와 end 사이의 값을 잘라옴

- toString(): String 출력

 

'알고리즘' 카테고리의 다른 글

슬라이딩 윈도우  (0) 2022.08.05
자바 조합  (0) 2022.08.03
자바 부분 집합  (0) 2022.08.03
자바 순열  (0) 2022.08.03