Java 忽略/清除用户输入中的额外整数

Java 忽略/清除用户输入中的额外整数,java,input,integer,Java,Input,Integer,我被困在程序的这一部分,用户输入多个整数,只选择第一个整数。在我当前的代码中,输出如下 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

我被困在程序的这一部分,用户输入多个整数,只选择第一个整数。在我当前的代码中,输出如下

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.
而在给定的示例中,输出是这样的

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在输入中的位置如何?在得到true或false后,如果没有添加新输入,下一个hasNextInt命令是否会在相同的输入位置查找


用**括起来的文本是用户输入。

如果不能确定用户是否正确输入,可以通过接受字符串而不是整数来完成。像这样:

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,将字符串拆分为围绕s的字符串数组,然后返回第一个,即您希望在索引0处返回的字符串


正如所写的那样,它没有做的是处理foobar42之类的输入,或者处理拆分字符串的第一个索引无法解析为整数的任何其他输入。尝试这样做将导致NumberFormatException。

请在问题中包含您的代码。添加您的代码。我猜您使用whilesc.hasNextInt{}而不是if。