View

https://www.acmicpc.net/problem/10952

 

10952번: A+B - 5

두 정수 A와 B를 입력받은 다음, A+B를 출력하는 프로그램을 작성하시오.

www.acmicpc.net

 

📚 문제

두 정수 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
Share Link
reply
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31