03_스캐너
result 3 입력 안했는데 값없이 출력되는이유
package com.ohgiraffers.section04.scanner;
import java.util.Scanner;
public class Test01 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// 정수형 입력받기
int result1 = sc.nextInt();
System.out.println("result1 = " + result1);
// 실수형 입력받기
double result2 = sc.nextDouble();
System.out.println("result2 = " + result2);
// 문자열 입력받기
String result3 = sc.nextLine();
System.out.println("result3 = " + result3);
String result4 = sc.next();
System.out.println("result4 = " + result4);
// 문자 입력받기
char result5 = sc.next().charAt(2);
System.out.println("result5 = " + result5);
// 형변환 해보기
int result6 = sc.nextInt();
System.out.println("result1 = " + (char)result6);
}
}
result 3 입력 안했는데 값없이 출력되는이유
Scanner 클래스의 nextLine() 메서드는 개행 문자를 만날 때까지 입력을 읽습니다. 따라서 nextLine() 이전에 nextInt() 또는 nextDouble() 등의 입력 메서드를 사용하고 나면, 엔터 키를 눌러 개행 문자가 입력 버퍼에 남아있게 됩니다.
이후에 **nextLine()**을 호출하면 남아있는 개행 문자가 입력으로 처리되어서 바로 넘어가는 문제가 발생합니다. 이를 해결하기 위해서는 nextInt() 또는 nextDouble() 이후에 **nextLine()**을 한 번 호출하여 입력 버퍼를 비워주는 것이 좋습니다.
package com.ohgiraffers.section04.scanner;
import java.util.Scanner;
public class Test01 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// 정수형 입력받기
int result1 = sc.nextInt();
System.out.println("result1 = " + result1);
// 실수형 입력받기
double result2 = sc.nextDouble();
System.out.println("result2 = " + result2);
// 개행 문자 처리
sc.nextLine();
// 문자열 입력받기
String result3 = sc.nextLine();
System.out.println("result3 = " + result3);
String result4 = sc.next();
System.out.println("result4 = " + result4);
// 문자 입력받기
char result5 = sc.next().charAt(2);
System.out.println("result5 = " + result5);
// 형변환 해보기
int result6 = sc.nextInt();
System.out.println("result1 = " + (char)result6);
}
}