2012-09-23 145 views
4

我在返回用戶輸入字符串時遇到困難。如果我有一個代碼:Java輸入字符串

System.out.println("please enter a digit: "); 
number1 = in.nextInt(); 
System.out.println("enter another digit: "); 
number2 = in.nextInt(); 
System.out.println("enter a string: "); 
string = in.nextLine(); 
//calculations 

System.out.println(number1); 
System.out.println(number2); 
System.out.println(string); 

它打印出數字而不是字符串。我覺得這個解決方案非常簡單,但我現在有一個大腦屁。任何幫助,將不勝感激!

+0

它給出了什麼輸出? –

+1

在調用in.nextLine()讀取字符串之前,您需要in.nextLine()。它是從讀取整數的上一行中消耗新的行字符。 – nhahtdh

+0

@nhahtdh:你應該發佈這個答案。 –

回答

8

您需要調用in.nextLine()字符串中讀取之前調用額外in.nextLine()。它會消耗額外的新行字符。

至於解釋,讓我們用這個輸入爲例:

23[Enter] 
43[Enter] 
Somestring[Enter] 

(23和43可以只是任意號碼,重要組成部分,是新線

您需要調用in.nextLine()消耗前一個in.nextInt()的新行,特別是上面示例中的43之後的新行字符。

nextInt()將消耗盡可能多的數字,並在下一個字符是非數字時停止,因此新行在那裏。 nextLine()將讀取所有內容,直到遇到新行。這就是爲什麼您需要額外的nextLine()刪除43後的新行,以便您可以繼續閱讀下一行的Somestring

如果,例如,你的投入是這樣的:

23 43 Somestring[Enter] 

你不按Enter鍵,只是不停地打字,那麼你當前的代碼將顯示該字符串(這將是 Somestring,請注意因爲43之後沒有新的線路阻塞。

4

int number2 = in.nextInt(); 

當你輸入號碼,然後按ENTER鍵傳遞一個字符串來聲明

string = in.nextLine(); 

。試圖讀取另一個將解決這個問題之前消費使用Scanner.nextLine()這串:

... 
number2 = in.nextInt(); 
in.nextLine(); 
System.out.println("enter a string: "); 
string = in.nextLine(); 
... 
1

在你的情況下,in.next()將足以讀取字符串,如果沒有空間之間。

1

String xxx;

掃描儀數字1 =新掃描儀(System.in)

XXX = number1.nextLine();