두 정수 A와 B를 입력받은 다음, A+B를 출력하는 프로그램을 작성하시오.
1 2
3
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int a = Integer.parseInt(scanner.nextLine());
int b = Integer.parseInt(scanner.nextLine());
System.out.println(a + b);
}
}
런타임 에러(NumberFormat)
예제 입력이 1 (스페이스) 2
로 되어 있었는데 당연히 1 (엔터) 2
일거라고 생각함
java.lang.NumberFormatException
: 문자열을 수로 변환할 때 발생하는 에러
: 입력받은 문자열 1 2
는 정수 하나로 변환할 수 없기 때문에 에러 발생
: 입력이 한 줄에 공백으로 구분되어서 들어오는 경우, 공백을 기준으로 문자열을 나눠서 처리해야 함
split()
메소드를 통해 공백 기준으로 문자열을 나눠 배열로 만들어 준 후 각각의 인덱스를 변수에 할당import java.util.Scanner;
public class Study {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] str = scanner.nextLine().split(" ");
int a = Integer.parseInt(str[0]);
int b = Integer.parseInt(str[1]);
System.out.println(a + b);
}
}