본문 바로가기

Coding Language/Java

[기억을 되돌리며#1] Buffered Reader를 이용한 데이터 입출력

Java Stdin and Stdout I

Most HackerRank challenges require you to read input from stdin (standard input) and write output to stdout (standard output).

One popular way to read input from stdin is by using the Scanner class and specifying the Input Stream as System.in. For example:

Scanner scanner = new Scanner(System.in);
String myString = scanner.next();
int myInt = scanner.nextInt();
scanner.close();

System.out.println("myString is: " + myString);
System.out.println("myInt is: " + myInt);

The code above creates a Scanner object named  and uses it to read a String and an int. It then closes the Scanner object because there is no more input to read, and prints to stdout using System.out.println(String). So, if our input is:Hi 5

Our code will print:

myString is: Hi myInt is: 5

Alternatively, you can use the BufferedReader class.

 

Task
In this challenge, you must read  integers from stdin and then print them to stdout. Each integer must be printed on a new line. To make the problem a little easier, a portion of the code is provided for you in the editor below.


문제는 엄청 간단하다.그냥 정수값 3개 입력해서 출력시키는 거다.심지어 문제안에 친절하게 "Scanner를 사용하세요~ 코드도 알려드릴게요." 하고 있다. 그리고 마지막 줄을 보면 BufferedReader가 대안 방법이라고 적혀있다. 

 

BufferedReader에 대해 개념부터 잡고 가도록 하자. BufferedReader는 입출력 장치로부터 입력받은 데이터를 Buffer라는 공간에 저장 후 특정 조건(버퍼가 가득 차거나 개행 문자 확인)에 만족하면 한 번에 내용을 프로그램에 전달한다.

 

외부 장치로부터 입력받은 데이터의 입출력이 생각보다 시간이 많이 걸린다. (비록 우리 눈에는 안 보이겠지만...)

따라서 중간에 Buffere라는 메모리 공간에 데이터를 가지고 있다가 뭉탱이채로 전달하기 때문에 입력 즉시 데이터가 전달되는 Scanner보다 BufferedReader가 더 효율적이다.

 

Oracle 공식 문서에서 보면 아래와 같이 객체를 생성하여 사용할 수 있다.

 BufferedReader in = new BufferedReader(new FileReader("foo.in"));

위의 코드는 File을 읽어 Buffer로 읽는 코드지만 내가 필요한 코드는 입력 장치로부터 숫자 값을 받아야 한다.

 

따라서 우리가 사용할 수 있는 방안은 InputStreamReader를 이용하는 것이다.

InputStreamReader는 Reader의 하위 클래스로 BufferedReader객체 생성 시 파라매터로 이용 가능하다.

BufferedReader(Reader in)
Creates a buffering character-input stream that uses a default-sized input buffer.

그리고 입력장치로부터 바이트 정보를 식별하기 위해 InputStream 중 하나인 System.in을 사용하면 된다.

InputStreamReader(InputStream in)
Creates an InputStreamReader that uses the default charset.

 

그러면 최종적으로 데이터를 Buffer에 저장 후 읽어올 수 있는 방법은 아래와 같이 된다.

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

 

BufferedReader를 통해 데이터를 읽을 땐 readLine() 메서드를 참고하면 된다.

그러나 String으로 고정되어 오기 때문에 원하는 타입으로 형변환을 시켜주도록 하자.

내가 필요한건 문자를 정수로 변경해야하니 Integer.parseInt를 이용하였다.

최종적으로 작성된 코드는 아래와 같다.

public class Solution {

    public static void main(String[] args) {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        
        try {
            for (int i = 0; i < 3; i++) {
                System.out.println(Integer.parseInt(br.readLine()));
            }
        } catch(IOException e) {
            e.printStackTrace();
        }
    }
}