백준 10951번| Java - A+B-4

bj1

풀이 1

import java.util.*;
public class Main {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		while(true) {		
			try {
				int a = sc.nextInt();
				int b = sc.nextInt();
				
				System.out.println(a+b);
				
			}catch(NoSuchElementException e) {
				break;
			}
		}
	}
}
  1. 더이상 읽어올 데이터가 없을 때 NoSuchElementException 예외가 발생하기 때문에 해당 예외가 발생했을 시 반복문이 종료되도록 try-catch 문을 사용했습니다.

풀이 2

import java.util.*;
public class Main {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		while(true) {		
			try {
				int a = sc.nextInt();
				int b = sc.nextInt();
				
				System.out.println(a+b);
		}
	}
}
  1. 더 간단한 풀이 방법이 있어서 다시 풀어보았습니다. hasNextInt() 메소드는 Scanner에서 정수를 입력받은 경우 true, 그렇지 않은 경우 false를 반환해줍니다.

comments powered by Disqus