22.12.16

Fromi·2022년 12월 16일
0

TIL

목록 보기
1/8
post-thumbnail

Scanner클래스 next(), nextLine()차이

next()

        String str1 = sc.next();
        System.out.println(str1);

입력 : Hello world
출력 : Hello

문자열(\s, \n로 구분) 입력
공백전까지 입력받음

nextLine()

        String str2 = sc.nextLine();
        System.out.println(str2);

입력 : Hello world
출력 : Hello world

문자열(1줄) 입력


next()함수 사용 후 nextLine()함수 사용시 원하는 문자 입력X

입력 		  	: Hello world
next()출력   	: Hello
nextLine()출력 	: (공백)world

next()에서 개행문자를 처리하지 못해서 버퍼에 남아있음(nextInt()도 마찬가지)
=> 버퍼에 남은 문자가 공백과 함께 nextLine()에 출력

해결하기 위해서는 두 함수 사이에 nextLine()함수 사용!

profile
https://github.com/c2540

0개의 댓글

관련 채용 정보