View
https://www.acmicpc.net/problem/10952
📚 문제
두 정수 A와 B를 입력받은 다음, A+B를 출력하는 프로그램을 작성하시오.
예제 입력 | 예제 출력 |
1 1 2 3 3 4 9 8 5 2 |
2 5 7 17 7 |
📝 문제 해결
while(true)를 하여 Scanner로 값을 받아주면 런타임 에러가 발생한다.
Scanner 클래스의 hasNextInt()를 사용하면 EOF처리가 된다.
sc.hasNextInt() 가 거짓일 경우 더 이상 입력이 없는 것으로 간주하여 종료한다.
💻 코드
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while( sc.hasNextInt()) {
int A = sc.nextInt();
int B = sc.nextInt();
System.out.println(A+B);
}
}
}
EOF(End of File) : 데이터 소스로부터 더 이상 읽을 수 있는 데이터가 없음을 뜻한다. (주어지는 입력을 그대로 출력)
- BufferedReader 클래스
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String input="";
while((input=br.readLine())!=null) {
//....
}
- Scanner 클래스
Scanner sc=new Scanner(System.in);
while(sc.hasNextLine()) {
sc.nextLine();
}
while(sc.hasNextInt()) {
sc.nextInt();
}
728x90
'알고리즘 > 백준' 카테고리의 다른 글
[1차원 배열] 백준 2566번 최댓값(Java) (0) | 2020.02.17 |
---|---|
[반복문] 백준 2439번 별 찍기-2(Java) (0) | 2020.02.14 |
[반복문] 백준 15552번 빠른 A+B(Java) (0) | 2020.02.14 |
reply