Java에서 하나의 스캐너 객체로 사용자 입력 int 및 문자열을 가져올 수없는 이유는 무엇입니까?

한 술 타나

사용자에게 int와 문자열을 가져 오려는 동일한 개체를 사용하여 스캔 한 개체를 호출했습니다.

Scanner scan = new Scanner(System.in);
//for a int 
int first_value  = scan.nextInt();
System.out.println(first_value); 
//for a string
String  first_name = scan.nextLine();
System.out.println(first_name); 

여기 콘솔은 문자열을 기다리지 않지만 다른 개체를 사용하면 정상적으로 작동합니다.

 Scanner insert = new Scanner(System.in);
 String name = insert.nextLine();

동일한 Scanner 객체를 사용하여 int와 string을 얻을 수 있습니까?

Sanjeev

그것은 int를 읽은 후 new line당신이 소비 한 문자를 남겼고 scan.nextLine다음 입력을 기다리지 않았기 때문입니다. 문자열을 읽기 전에 소비해야합니다.

Scanner scan = new Scanner(System.in);
//for a int 
int first_value  = scan.nextInt();
scan.nextLine();
System.out.println(first_value); 
//for a string
String  first_name = scan.nextLine();
System.out.println(first_name)

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

Related 관련 기사

뜨겁다태그

보관