2013-10-21 59 views
0
System.out.print("Name : "); 
    String name = in.nextLine(); 

    System.out.print("Age : "); 
    int age = in.nextInt(); 

    System.out.print("City : "); 
    String city = in.nextLine(); 

輸出將是:用戶輸入的字符串和整數在Java中

名稱:測試

年齡:20

生成成功

當我進行調試,它贏得了」閱讀「城市」的用戶輸入。但是當我將「年齡」的數據類型更改爲字符串時,它會讀取。我怎樣才能使系統讀取城市用戶輸入的數據類型爲int?

+0

@ athirahhazira94,你已經經歷關於nextLine()。 Anda kena baca tentang nextLine()。 – gjman2

回答

5

中仍存在的緩衝區的新行字符讀歲以後,將其更改爲..

System.out.print("Name : "); 
String name = in.nextLine(); 

System.out.print("Age : "); 
int age = in.nextInt(); 
//add 
in.nextLine(); 

System.out.print("City : "); 
String city = in.nextLine(); 
+1

發佈*爲什麼*這種補充是必要的,只是針對遇到此問題的任何其他人可能會有所幫助。 –

+0

是的。我同意@dennis。爲什麼這是必要的? –

+0

我也同意,所以現在就完成了 –

2

還有在緩衝區的新行字符讀歲以後。在詢問城市價值之前,嘗試添加in.nextLine

1

試試這個,

System.out.print("Age : "); 
int age = Integer.parseInt(in.nextLine()); 
相關問題