2016-02-06 27 views
0

我正在一個更大的程序中工作,我有一個while循環提出兩個問題並獲取兩個輸入。每當while循環的第二個循環發生時,它將顯示兩個輸出,而不是在第一個輸入之後接收輸入,然後將輸入作爲第二個輸入。雖然循環不能用於兩個輸入

這裏是一個小例子來說明我的問題:

public class Tests{ 

    public static void main(String args[]){ 

     Scanner Scan = new Scanner(System.in); 

     while (true){ 

      System.out.println("Please enter your name: "); 
      String name = Scan.nextLine(); 
      System.out.println("Please enter your age: "); 
      int age = Scan.nextInt(); 

      System.out.println(name + age); 
     } 
    } 
} 

通過優秀作品的第一個循環。然後第二次通過,它輸出

Please enter your name: 
Please enter your age: 

它跳過第一個輸入後的每個循環。 爲什麼?

回答

1

你需要調用

Scan.nextLine(); 

int age = Scan.nextInt(); 

這會消耗在緩衝行字符結束後。

另一種方法將是使用scan.nextLine()和解析輸入到這樣的整數:

int age = Integer.parseInt(Scan.nextLine()); 
+0

哦沒關係,由於 –