2014-12-03 98 views
1

當過我運行這個輸出是:do-while循環需要一個int還是一個字符串?

「請輸入您的姓名」 我進入它

「請輸入學號」 我進入它

「請輸入學生姓名」

「請輸入學號」

String nameChoice = ""; 

do{ 

     System.out.println("Please input the students name"); 

     String name = s.nextLine(); 
     nameChoice = name; 

     System.out.println("Please enter that students number"); 
     int studentNo = s.nextInt(); 



}while(!nameChoice.equalsIgnoreCase("done")); 

回答

1

這是因爲s.nextInt()只讀入輸入的整數,而不是輸入整數後的換行符。所以你可以添加一個s.nextLine()來閱讀這個換行符。

所以這樣做:

int studentNo = s.nextInt(); 
s.nextLine(); 

如果你不這樣做下一個nextLine()方法將被用來讀取輸入的換行符。

避免這個問題使用nextLine(),並將其解析來integer正在讀取的另一種方法。

int studentNo = Integer.parseInt(s.nextLine()); 
相關問題