背景:这是一个简单程序的最终循环,其中用户首先输入任意数量的整数( double )命令行参数,然后我将它们放入长度为 [args.length] 的数组中,然后我允许用户输入任何整数并检查它是否在数组中。我希望循环结束并且程序仅在用户输入字符串“exit”时终止。
但我不知道该怎么做。当然,解决这个问题不会太难。 (P.S. 我一开始就做了一个静态扫描仪方法,所以我的问题并不像计算机那样“你不能两次调用同一个 stdin 先生,白痴!”)。
while (true) {
double userstdin = stdin.nextDouble();
String exit = stdin.nextLine();
if (contains(arguments, userstdin) == true) {
System.out.println("This number is in your array.");
}
else if (contains(arguments, userstdin) == false) {
System.out.println("This number is not in your array.");
}
if (exit.equals("exit")) {
System.out.println("Terminating.");
return;
}
}
我需要用户能够输入数字或“退出”一词。我怎样才能在我的循环中做到这一点?
最佳答案
如果您需要用户能够在单个输入中输入多种类型的数据,请将其作为字符串获取,然后解析它以确定您实际获得的数据类型。
假设您的场景是用户可以输入数字或“退出”一词。任何其他输入均无效。
首先,捕获用户提供给您的任何内容——字符串、数字等:
String input = stdin.nextLine();
然后尝试将其解析为您的用例:
if("exit".equalsIgnoreCase(input)) {
// user entered exit
System.exit(0);
}
// Check to see if it's a number. There's a number of ways to do this, but for simplicity's
// sake, we'll just try to parse it.
try {
Double number = Double.parseDouble(input);
// do something here with number;
} catch (NumberFormatException e) {
// it was not a double, whatever it was.
// put some error handling here, maybe a message about a bad/unrecognized input
}
请注意,像这样检查数据类型被认为是不好的做法(例如,尝试解析然后在失败时捕获异常。)我在这里只是作为该技术的说明。
关于java - 一个循环中的不同扫描仪数据类型。该怎么办?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43243266/