2016-09-30 31 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