2011-03-24 10 views
4

을 묻는 난이 있습니다 : 그것은 문자열을 입력하시기 바랍니다 얻을 때입력하지

Scanner input = new Scanner (System.in); 
int selection = input.nextInt(); 
if (selection == 1) { 
System.out.println("Please enter a string: "); 
String code = input.nextLine(); 
} 

그러나, 그것은 모든 입력을 요청 나던을. 프로그램의 나머지 부분으로 이동합니다.

+0

이 질문에 무관하지만,이 같은 콘솔 입력을 수행 할 때 대신 println''의 print''사용해야 있도록 어떤에서 사용자 유형 콘솔은 콜론 뒤에 있습니다 (같은 줄에 있음). 'System.out.print ("문자열을 입력하십시오 :");' –

답변

6

Scanner은 사용자가 enter를 누를 때까지 nextInt()에서 기다립니다. 그런 일이 발생하면 숫자가 소모되지만 이 아니라 새 줄 문자 자체가 소모됩니다. 따라서 nextLine()에 대한 다음 호출은 빈 값 String을 즉시 반환합니다.

int selection = input.nextInt(); 
input.nextLine(); 
if (selection == 1) { 
    System.out.println("Please enter a string: "); 
    String code = input.nextLine(); 

하지만 내 선호하는 방법은 항상 nextLine를 사용하여 개별적으로 분석하는 것입니다 :

이 그것을 수정해야 당신의 nextInt 후

input.nextLine(); 

:

String selectionStr = input.nextLine(); 

//consider catching a NumberFormatException here to handle erroneous input 
int selection = Integer.parseInt(selectionStr); 

if (selection == 1) { 
    System.out.println("Please enter a string: "); 
    String code = input.nextLine(); 
    //... 
+0

+1 항상'nextLine'을 사용하고 당신이 원하는 것을 파싱하도록 제안하십시오. –

0

시도();

Scanner input = new Scanner(System.in); 
int selection = input.nextInt(); 
input.nextLine(); 
System.out.println(selection); 
if (selection == 1) { 
    System.out.println("Please enter a string: "); 
    String code = input.nextLine(); 
} 
+1

이 답변이 정말로 필요한가요? 당신은 @ Mark의 대답을 읽을 때까지 답을 직접 알지 못했습니다. –

+1

당신이 내 대답을 좋아하지 않는다면 그것을 읽지 마라. – smas

0

간단한 & 그래픽 입력 :

String str=JOptionPane.showInputDialog(null,"Message","Title",JOptionPane.QUESTION_MESSAGE); 
관련 문제