[Java] Scanner nextInt() + nextLine() 본문

Troubleshooting

[Java] Scanner nextInt() + nextLine()

miensoap 2024. 1. 26. 21:35

문제

- 백준 10828번 풀이 중 StirngTokenizer.nextToken 에서 NoSuchElementException 발생

public class P10828 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        StackIpl stk = new StackIpl();
        int n = sc.nextInt();
        sc.nextLine(); // 해결

        for (int i = 0; i < n; i++){
            StringTokenizer st = new StringTokenizer(sc.nextLine());
            String cmd = st.nextToken();

 

해결

- Scanner.nextInt() 후 버퍼에 개행문자 \n이 남아있어 nextLine()에 입력되어 의도하지 않은 결과가 나타남.

 

-> 중간에 nextLine()을 추가하여 버퍼를 비워줌

'Troubleshooting' 카테고리의 다른 글

UndeclaredThrowableException?? (2)  (0) 2024.06.02
UndeclaredThrowableException?? (1)  (0) 2024.06.02