背景:这是一个简单程序的最后一个循环,在该程序中,用户首先输入任意数量的整数(双)命令行参数,然后将它们放入长度为[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;
}
}
我需要用户能够输入数字或单词“ exit”。如何在循环中执行此操作?
最佳答案
如果您需要用户能够在单个输入中输入多种类型的数据,请以字符串形式获取它,然后解析它以确定您实际获得的数据类型。
假设您的情况是用户可以输入数字或单词“ exit”。其他任何输入均无效。
首先,捕获用户给您的任何内容(字符串,数字或其他内容):
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
}
请注意,检查这样的数据类型被认为是不好的做法(例如,尝试解析然后在失败时捕获Exception。)我在这里只是为了说明该技术。