2016-09-30 32 views
-2

我被困在程序的這部分用戶輸入多個整數,只有第一個被選中。在我當前的代碼中,輸出是這樣的。忽略/清除用戶輸入的額外整數

There are 10 sticks on the board. 
Jerry: How many sticks do you take (1-3)? *1 3 4 2* 
There are 9 sticks on the board. 
Sherry: How many sticks do you take (1-3)? There are 6 sticks on the board. 
Jerry: How many sticks do you take (1-3)? Please enter a number between 1 and 3. 
Jerry: How many sticks do you take (1-3)? There are 4 sticks on the board. 
Sherry: How many sticks do you take (1-3)? 

雖然在給出的例子中,輸出是這樣的。

Jerry: How many sticks do you take (1-3)? *1 3 4 2* 
There are 8 sticks on the board. 
Pat: How many sticks do you take (1-3)? *3* 
There are 5 sticks on the board. 

似乎額外的整數正在排隊等待下一個掃描儀輸入命令。在給定的例子中,額外的整數被清除。這是如何完成的?是否有清除所有當前用戶輸入的命令,或是使用.hasNextInt讀入的所有整數,並且第一個過去的數據只是簡單地丟棄?另外,hasNextInt在輸入中查找的地方是什麼?如果沒有添加新輸入,那麼在得到真或假之後,下一個hasNextInt命令是否會查看相同的輸入位置?

(由**包圍的文字是用戶輸入。)

+0

請在問題中包含您的代碼。 – fvu

+0

添加您的代碼。我猜你使用'while(sc.hasNextInt()){}'而不是'if'。 –

回答

0

如果你不能確定用戶將輸入正確的輸入,可以通過接受String!而非int做吧。像這樣:

Scanner s = new Scanner(System.in); 
System.out.print("How many?: "); 
int many = Integer.parseInt(s.nextLine().trim().split(" ")[0]); 
System.out.println(many); 

這甚至會處理這樣" 2 5 6 5"輸入以及你有例子通過將整個輸入字符串,修剪掉任何前端和後端" " S,分裂串入的String秒的陣列周圍" " s,然後返回索引0處的第一個(您想要的那個)。

它不會像寫入的那樣處理輸入,如" foo bar 42"或任何其他輸入,其中split字符串的第一個索引不能被解析爲整數。試圖這樣做將導致NumberFormatException