개발/Java

☕️Java:: nextInt() 사용 후 nextLine() 사용시의 문제 해결하기

hyuunii 2023. 8. 11. 09:13

예컨대 첫줄에 인티져, 둘쨋줄에 스트링의 입력이 있다고 하자.

이때, 자바의 nextInt()는 해당 줄의 인티져만 인식하고 마지막의 개행문자는 안받는다.

nextInt() 후 nextLine()을 쓰면 걔가 같이 개행문자를 받아버린다.

 

어떤 식이냐면

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
 
        int 숫자 = sc.nextInt();
        String 글자 = sc.nextLine();
        String 문자 = sc.nextLine();
 
        System.out.println("숫자 :" + 숫자);
        System.out.println("글자: " + 글자);
        System.out.println("문자: " + 문자);
    }
}
 
cs

입력

7520
글자다

 

출력
숫자 :7520
글자: 
문자: 글자다

 

 

 

결론(해결법):: 위와 같이 nextLine()을 한 번 더 써줘야 두번째줄의 String '글자다'를 인식해서 받아온다.