...

[JAVA] Scanner의 next() / nextLine() 차이점 본문

언어/JAVA 자바

[JAVA] Scanner의 next() / nextLine() 차이점

gi2 2022. 2. 18. 15:39

next()

-> '토큰'의 개념으로서 문자열을 입력받는다.

따라서 앞뒤 공백이나 스페이스가 구분자로 인식되어 입력값으로 들어오지 않는다.

 

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        String s;
        while(sc.hasNext()) {
            s = sc.next();

            System.out.println(s);
        }
    }
}

 

 

nextLine()

->  nextLine()은 토큰 단위로 입력값을 받아오는 게 아닌 콘솔창의 한 문장을 간격으로 입력값을 받아온다.

따라서 앞뒤에 공백이 있거나 중간에 space가 있어도 이를 구분자로 사용하지 않고 모두 받아올 수 있다

 

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        String s;
        while(sc.hasNextLine()) {
            s = sc.nextLine();

            System.out.println(s);
        }
    }
}

Comments