【问题标题】:Ignoring/Clearing Extra integers from user input忽略/清除用户输入中的额外整数
【发布时间】:2016-09-30 22:15:41
【问题描述】:

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

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 命令是否会查找相同的输入位置?

(**括起来的文字是用户输入的。)

【问题讨论】:

  • 请在问题中包含您的代码。
  • 添加您的代码。我猜你使用while(sc.hasNextInt()) {} 而不是if

标签: java input integer


【解决方案1】:

如果您不能确定用户将正确输入输入,您可以通过接受Strings 而不是ints 来做到这一点。像这样:

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,将字符串拆分为Strings 周围的数组987654327@s,并返回索引0处的第一个(您想要的)。

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

【讨论】:

    猜你喜欢
    • 2022-09-24
    • 1970-01-01
    • 2019-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-10
    • 1970-01-01
    相关资源
    最近更新 更多