Java 尝试在用户输入不正确时捕获的捕获
我想知道如何做到这一点,这样用户既可以选择不输入整数,也可以在用户不输入整数的情况下捕获并重新提示他们,而不会结束程序。我需要扫描仪同时接收int和string类型。有办法做到这一点吗?还是绕道而行Java 尝试在用户输入不正确时捕获的捕获,java,Java,我想知道如何做到这一点,这样用户既可以选择不输入整数,也可以在用户不输入整数的情况下捕获并重新提示他们,而不会结束程序。我需要扫描仪同时接收int和string类型。有办法做到这一点吗?还是绕道而行 /* The following method asks a user to input a series of integers. * The user can stop at any time buy entering "quit" */ public static void readSe
/* The following method asks a user to input a series of integers.
* The user can stop at any time buy entering "quit"
*/
public static void readSeries()
{
int integer;
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a series of integers. If you wish to stop, enter 'quit'. ");
System.out.println();
try{
while(true)
{
System.out.println("Enter an integer: "); // asks user to enter an integer
integer = scan.nextInt();
if(scan.equals (0)){break;} // allows user to stop entering numbers
}
} catch(NumberFormatException nfe){System.out.println("Invalid Entry!");}
}
}
从分解你的需求开始 首先,您需要能够从用户处读取文本和
int
值。您需要能够这样做,因为您需要检查“退出”条件。因此,您不应该使用Scanner\nextLine
,而应该使用Scanner\nextLine
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
将是合适的(在循环结束而不是开始时检查循环的退出条件)
因此,当循环存在时,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");
列表值=新的ArrayList(25);
整数值=null;
做{
value=promptForInt(“请输入一系列整数。如果要停止,请输入'quit'”,新扫描仪(System.in),“quit”);
if(值!=null){
增加(价值);
}
}while(值!=null);
System.out.println(“您有输入”+值.size()+“有效整数”);
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");