프로그래밍/JAVA
JAVA next(), nextLine() 차이점
moon1226
2019. 7. 10. 16:55
- next()와 nextLine() 차이점
next() : 문자 또는 문자열을 공백기준으로 한 단어로 입력받음.
nextLine() : 문자 또는 문자열을 한 라인 전체로 입력받음.
- 문제 상황
public class test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int first = sc.nextInt();
String second = sc.nextLine();
System.out.println(first + second);
}
}
다음과 같은 코드일 때, scanner 입력을 받는다면
[입력]
123 word
[출력]
123word
으로 입력해야 first에 123, second에 word가 들어간다.
하지만 123을 치고 엔터를 친다면,
[입력]
123
//엔터를 치면 프로그램이 끝난다.
[출력]
123
second 입력을 받기 전에 프로그램이 끝난다.
- 해결법
public class test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int first = sc.nextInt();
String second = sc.next();
System.out.println(first + second);
}
}
다음과 같이 next()를 이용하면 엔터를 치고 second를 입력받는 것이 가능하다.
[입력]
123
word
[출력]
123word