티스토리 뷰

[표준입출력] nextInt(), nextLine() 차이

  • 문제

    int, double, String을 순서대로 입력받은 다음에, String, Double, int 순으로 다시 출력하는 문제

     

  • 잘못된 코드(1)

    import java.util.Scanner;
    
    public class Solution {
    
        public static void main(String[] args) {
            Scanner scan = new Scanner(System.in);
            int i = scan.nextInt();
            double d =scan.nextDouble(); 
            String s = scan.nextLine();
    
            System.out.println("String: " + s);
            System.out.println("Double: " + d);
            System.out.println("Int: " + i);
        }
    }
    

    nextInt(), nextDouble() 메서드는 사용자가 마지막으로 입력한 숫자까지만 입력받고, 그 이후의 엔터는 처리하지 않음. 그래서 뒤에 바로 nextLine()을 사용하면 그 엔터가 해당 메서드의 입력으로 처리되어서 입력이 종료되는 문제가 발생한다.

     

  • 잘못된 코드(2)

    import java.util.Scanner;
    
    public class Solution {
    
        public static void main(String[] args) {
            Scanner scan = new Scanner(System.in);
    
            int i = scan.nextInt();
            double d =Double.parseDouble(scan.nextLine()); // Error! 
            String s = scan.nextLine();
    
    
            System.out.println("String: " + s);
            System.out.println("Double: " + d);
            System.out.println("Int: " + i);
        }
    }
    

    nextLine()은 사용자가 마지막으로 입력한 엔터까지 처리하므로, nextLine()으로 받아 parseDouble()했지만 이 경우 앞에 nextInt()가 있어서 문제가 된다. nextInt()에서 숫자를 입력받은 다음 엔터를 쳤을 때, 이 것이 바로 nextLine()의 입력으로 간주되고 그 다음에 double로 파싱하려고 할 때에 전달받은 것이 비어있으므로 empty String 에러가 나게 된다. 그래서 이 방법을 쓰려면 앞의 int까지 nextLine()으로 전달받은 다음 int로 파싱하여야 한다.

     

  • import java.util.Scanner;
    
    public class Solution {
    
        public static void main(String[] args) {
            Scanner scan = new Scanner(System.in);
            int i = scan.nextInt();
            double d =scan.nextDouble(); 
            scan.nextLine();
            String s = scan.nextLine();
    
            System.out.println("String: " + s);
            System.out.println("Double: " + d);
            System.out.println("Int: " + i);
        }
    }
    

    nextDouble()뒤에 nextLine()을 한 번 더 사용하여 엔터를 처리하도록 하고, 이 후에 String을 입력받도록 하면 된다.

    또는 앞의 int와 double모두 nextLine()으로 받은 뒤 파싱하면 된다.

'Java' 카테고리의 다른 글

[자바] 제네릭스 문제로 이해하기  (0) 2019.05.30
[자바] 제네릭스(Generics) - 1  (0) 2019.05.29
JDBC 데이터 삽입, 수정, 삭제  (0) 2019.05.22
JDBC  (0) 2019.05.22
직렬화  (0) 2019.05.14
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
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 30
글 보관함