바킹독 강의는 기본적으로 C++ 기준으로 진행하기에 java의 입출력에 대한 클래스를 스스로 조사해야했다.
이건 필자가 [백준 10871] X보다 작은 수 문제를 Java로 처음 풀어봤었던 문제이다.
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int x = sc.nextInt();
int[] A = new int[n];
for (int i = 0; i < n; i++) {
A[i] = sc.nextInt();
}
sc.close();
for (int i = 0; i < n; i++) {
if (A[i] < x) {
System.out.print(A[i] + " ");
}
}
}
}
Java로 입력을 받으려면 Scanner 를 사용해야한다는 것은 알고있었으나 시간적인 손해를 본다고 한다.
해서~ Java 로 코딩 테스트를 준비하는데 있어서 필수적인 클래스들을 ARABO 려고 한다.
자바에서 사용자가 입력한 문자열을 얻기 위해서는 다음과 같이 System.in을 사용한다.
import java.io.IOException;
import java.io.InputStream;
publicclassSample {
publicstaticvoidmain(String[] args)throws IOException {
InputStream in = System.in;
int a;
a = in.read();
System.out.println(a);
}
}
InputStream 이란 클래스가 나왔다. 해당 클래스의 read 메소드는 1byte 크기의 사용자 입력을 int 자료형으로 받아들인다. 해당 코드를 실행시키고 문자를 치게되면 아스키 코드로 받을 것이다.
throws IOException?
InputStream으로부터 값을 읽어 들일 때는 IOException라는 예외가 발생할 수 있기 때문에 이를 처리
만약 3개 이상의 문자의 아스키코드 값을 받고싶다면
import java.io.IOException;
import java.io.InputStream;
public class Sample {
public static void main(String[] args) throws IOException {
InputStream in = System.in;
byte[] a = new byte[3];
in.read(a);
System.out.println(a[0]);
System.out.println(a[1]);
System.out.println(a[2]);
}
}
를 실행하면 된다.
read() : inputStream의 메서드. 1byte 크기의 자료를 int 로 받아들인다.
아스키 값으로 출력하지 않고 문자 그대로를 저장해야할때 해당 클래스를 사용하면 된다.
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class Sample {
public static void main(String[] args) throws IOException {
InputStream in = System.in;
InputStreamReader sr = new InputStreamReader(in);
char[] a = new char[3];
sr.read(a);
System.out.println(a);
}
}
InputStreamReader 객체를 생성하기 위해서는 InputStream 객체가 필요하다.
InputStream in = System.in;
InputStreamReader sr = new InputStreamReader(in);

물론 char[] a = new char[3]; 했기에 3개만 인식된다.
그렇다면 길이에 상관없이 사용자가 입력한 값을 모두 받아들일 수는 없을까?
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
public class Sample {
public static void main(String[] args) throws IOException {
InputStream in = System.in;
InputStreamReader sr = new InputStreamReader(in);
BufferedReader br = new BufferedReader(sr);
String a = br.readLine();
System.out.println(a);
br.close()
}
}
BufferedReader는 객체를 생성할 때 생성자의 입력으로 InputStreamReader의 객체가 필요하다.
BufferedReader는 문자열 스트림을 버퍼에 저장해두기에 마무리에 항상 닫아주도록 하자.
파이썬의 split과 비슷하다. 문자열을 구분자 기준으로 토큰화하여 구성할 수 있다.
| 리턴값 | 메서드명 | 역할 |
|---|---|---|
| boolean | hasMoreTokens() | 남아있는 토큰이 있으면 true를 리턴, 더 이상 토큰이 없으면 false 리턴 |
| String | nextToken() | 객체에서 다음 토큰을 반환 |
| String | nextToken(String delim) | delim 기준으로 다음 토큰을 반환 |
| boolean | hasMoreElements() | hasMoreTokens와 동일한데 엘리먼트보다 토큰으로 된 메서드를 주로 사용 |
| Object | nextElement() | nextToken 메서드와 동일하지만 문자열이 아닌 객체를 리턴 |
| int | countTokens() | 총 토큰의 개수를 리턴 |
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) {
String str = "Hello, world!";
StringTokenizer st = new StringTokenizer(str, " ");
while(st.hasMoreTokens()){
System.out.println(st.nextToken());
}
}
}
StringTokenizer(str, " ") 를 이용해 스트링을 띄어쓰기 기준으로 나눠 출력하는 코드.
이제 배운 코드를 활용하면 첫번재 문제를 다음과 같이 고칠 수 있다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException {
// BufferedReader를 사용
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int x = Integer.parseInt(st.nextToken());
int[] A = new int[n];
// 두 번째 줄에서 배열 A의 요소들을 입력받고, 동시에 x보다 작은 요소를 한번에 처리
st = new StringTokenizer(br.readLine());
StringBuilder result = new StringBuilder();
for (int i = 0; i < n; i++) {
A[i] = Integer.parseInt(st.nextToken());
if (A[i] < x) {
// x보다 작은 요소들을 StringBuilder에 추가
result.append(A[i]).append(" ");
}
}
System.out.println(result.toString());
br.close();
}
}