首先打破你的要求。
首先,您需要能够从用户那里读取文本和int 值。您需要能够执行此操作,因为您需要检查“退出”条件。因此,您应该使用Scanner#nextLine,而不是使用Scanner#nextInt。
String input = scan.nextLine();
接下来,您需要检查用户的输入是否满足“退出”条件。如果不是,您需要尝试将输入转换为 int 值并处理可能发生的任何转换问题
Integer value = null;
//...
if (escape.equalsIgnoreCase(input)) {
exit = true;
} else {
try {
value = Integer.parseInt(input);
} catch (NumberFormatException exp) {
System.out.println("!! " + input + " is not a valid int value");
}
}
好的,一旦你的工作正常,你需要将它包装在循环的一侧,现在,因为我们必须至少循环一次,do-while 将是合适的(检查循环的退出条件循环结束而不是开始)
Integer value = null;
boolean exit = false;
do {
System.out.print(prompt);
String input = scanner.nextLine();
if (escape.equalsIgnoreCase(input)) {
exit = true;
} else {
try {
value = Integer.parseInt(input);
} catch (NumberFormatException exp) {
System.out.println("!! " + input + " is not a valid int value");
}
}
} while (value == null && !exit);
因此,当循环存在时,value 将是一个有效整数或null。你可能会想为什么这很重要。 null 让我们知道它们不再是来自用户的有效值,否则您需要提出一个 int 退出值,但如果用户选择使用该值作为他们的输入会发生什么?
好的,现在,我们需要多次要求用户这样做,所以,这需要一个方法!
public Integer promptForInt(String prompt, Scanner scanner, String escape) {
Integer value = null;
boolean exit = false;
do {
System.out.print(prompt);
String input = scanner.nextLine();
if (escape.equalsIgnoreCase(input)) {
exit = true;
} else {
try {
value = Integer.parseInt(input);
} catch (NumberFormatException exp) {
System.out.println("!! " + input + " is not a valid int value");
}
}
} while (value == null && !exit);
return value;
}
现在,您可以简单地使用另一个循环来根据需要多次调用该方法
List<Integer> values = new ArrayList<>(25);
Integer value = null;
do {
value = promptForInt("Please enter a series of integers. If you wish to stop, enter 'quit'. ", new Scanner(System.in), "quit");
if (value != null) {
values.add(value);
}
} while (value != null);
System.out.println("You have input " + values.size() + " valid integers");