1. 목적
파일의 끝(EOF)을 올바르게 판단하는 법을 연습한다.
총 몇 줄이 주어진다 등의 정보는 입력으로 주지 않는다.
1-1. EOF란?
EOF(End Of File, 파일끝) 처리로 끝낸다.
- EOF란 : 데이터 소스로부터 더 이상 읽을 수 있는 데이터가 없음을 나타낼때를 말한다.
입력부분의 기준이 없는 문제를 접할 때 사용할 수 있다.
자바에서는 hasNextLine()과 NextLine을 사용한다.(Scanner 이용)
2. 방법(JAVA)
- (Java) Scanner의 메서드들은 NoSuchElementException을 던진다.
- (Java) BufferedReader.readLine()은 null을 반환한다.
① Scanner 사용
- Scanner 로 입력을 받는다.
- 입력받는 값이 있으면 A,B 입력받고 합을 출력하는 과정을 반복한다.
- hasNext(), hasNextInt() 사용 가능
public class Main {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
int a = sc.nextInt();
int b = sc.nextInt();
System.out.println(a+b);
}
sc.close();
}
}
② BufferedReader 사용
public class Main {
public static void main(String[] args) throws IOException{
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = "";
while((input=br.readLine())!=null) {
StringTokenizer st = new StringTokenizer(input);
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
bw.write(String.valueOf(a+b));
bw.newLine();
}
bw.flush();
bw.close();
br.close();
}
}
'Study > [Algorithm]' 카테고리의 다른 글
[백준] 2941번 - 크로아티아 알파벳 (0) | 2021.05.29 |
---|---|
[백준] 1929번 - 소수 구하기 (0) | 2021.05.28 |
[백준] 1152번 JAVA - 단어의 개수 (0) | 2021.05.27 |
[백준] 2577번 JAVA - 숫자의 개수 (0) | 2021.05.21 |
[백준] 1110번 JAVA - 더하기 사이클 (0) | 2021.05.20 |
댓글