본문 바로가기

카테고리 없음

Er1) nextLine() 메소드가 그냥 넘어가는 이유

nextIntI() 메소드 다음으로 nextLine() 메소드를 실행하려고 할때, nextLine() 메소드가 그냥 넘어가버리는 문제의 예제 및 해결방법. 

 

 

 

 

< 예제1 > 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package Error_S01;
 
import java.util.Scanner;
 
public class test {
    
    public static void main(String[]args) {
        Scanner scanner = new Scanner(System.in);
        
        int num = 0;
        String str = "";
        
        
        System.out.println("정수를 입력하세요.");
        num = scanner.nextInt();
        
        System.out.println("문자열을 입력하세요.");
        str = scanner.nextLine();
        
        System.out.println("두 번째 정수를 입력하세요.");
        num  = scanner.nextInt();
        
        
    }
    
    
}
 
cs

 

< 예제1의 출력결과> 

 

 

문제 이유> 

 

nextInt() 메소드 실행 시 20을 콘솔에 입력하고, 엔터를 누를 때 20을 리턴시키고 Enter값은 그대로 남아있다. 즉 엔터의 앞부분 까지만 입력을 받는다. 이러한 개행문자(Enter)를 제거하지 않아 그 다음 나오는 nextLine()이 실행될 때 이전의 개행문자(엔터)를 받게 되어 바로 종료되는 것이다. 

 

해결 방법> 


이를 해결하고싶다면 정수를 입력하고, 그 다음 문자를 입력하려고 할 때 *next() 메소드를 사용하거나, 위에 **nextLine() 메소드를 한번 더 작성해주어 enter값을 없애주면 된다.

 


*  next() : 스페이스, 즉 공백 전까지 입력받은 문자열을 리턴한다.
 ** nextLine() : Enter를 치기 전까지 쓴 문자열을 모두 리턴한다. 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package Error_S01;
 
import java.util.Scanner;
 
public class test {
    
    public static void main(String[]args) {
        Scanner scanner = new Scanner(System.in);
        
        int num = 0;
        String str = "";
        
        
        System.out.println("정수를 입력하세요.");
        num = scanner.nextInt();
        scanner.nextLine();
        
        System.out.println("문자열을 입력하세요.");
        str = scanner.nextLine();
        
        System.out.println("두 번째 정수를 입력하세요.");
        num  = scanner.nextInt();
        
        
    }
    
    
}
 
cs