[英]What's the problem about my code? It crashes
When the user enters an input like 0 or 6, the program enters an endless loop.当用户输入像 0 或 6 这样的输入时,程序进入一个无限循环。
I tried to create new while loops, break and continue statements.我尝试创建新的 while 循环、break 和 continue 语句。 However, none of them worked.然而,他们都没有工作。
public static final Pattern p12345 = Pattern.compile("[1-5]");
public Counter() {
this.counter = 0;
// System.in is like System.out, however, for input and not for output.
Scanner s = new Scanner(System.in);
/*
* can take value 1 (add) 2 (subtract) 3 (show counter) 4 (set counter) 5 (exit)
*/
int topChoice = 0; // Can be anything but 5 to enter the loop
while (topChoice != 5) {
System.out.println("Please enter:\n" + "1 to add to the total\n" + "2 to subtract from the total\n"
+ "3 to show the total\n" + "4 to set the total\n" + "5 to exit the program");
try {
topChoice = Integer.parseInt(s.next(p12345));
} catch (InputMismatchException e) {
System.out.println("You need to enter an integer between 1-5.");
}
switch (topChoice) {
case 1:
add(s);
break;
case 2:
subtract(s);
break;
case 3:
show();
break;
case 4:
set(s);
break;
case 5:
System.out.println("Finally there are " + counter + " items available.");
break;
default:
throw new IllegalArgumentException();
}
}
}
When the user enters an integer which is not in range of 1-5, I expected to turn back and ask again, but it crashes.当用户输入一个不在 1-5 范围内的 integer 时,我希望回头再问一次,但它崩溃了。
Please enter:
1 to add to the total
2 to subtract from the total
3 to show the total
4 to set the total
5 to exit the program
6
You need to enter an integer between 1-5.
Exception in thread "main" java.lang.IllegalArgumentException
at Counter.<init>(Counter.java:87)
That is because of this line of code:那是因为这行代码:
default:
throw new IllegalArgumentException();
I assume you are getting an error in the console for IllegalArgumentException right?我假设您在控制台中收到 IllegalArgumentException 错误,对吗? Having not declared a case for 0-6, the switch statement will by default go to the default case, where you throw an exception在没有声明 0-6 的情况下,switch 语句默认情况下将 go 转换为默认情况,在这种情况下抛出异常
You can simplify your code much more.您可以进一步简化代码。 What I mean is you can use a simple if-else
statement checking for the range of 1 to 5 instead of the try-catch
that would throw an IllegalArgumentException
with the Pattern
class.我的意思是您可以使用一个简单的if-else
语句检查 1 到 5 的范围,而不是使用try-catch
来抛出带有Pattern
class 的IllegalArgumentException
。 The else
statement can be a console print saying that the number was out of range. else
语句可以是控制台打印,说明数字超出范围。 Also, I'm assuming you're supposed to increment your counter
variable by 1 for each iteration of the while
loop?另外,我假设您应该为while
循环的每次迭代将counter
变量增加 1? I don't see that in your code.我在你的代码中没有看到。
Revised:修改:
while (topChoice != 5) {
counter++;
try {
topChoice = Integer.parseInt(s.next());
}
catch (NumberFormatException er)
{
System.out.println("Error: You must enter in an integer.");
}
catch (Exception er)
{
System.out.println("Error: " + er.getMessage());
}
if (topChoice >= 1 && topChoice <= 5)
{
switch (topChoice) {
case 1:
add(s);
break;
case 2:
subtract(s);
break;
case 3:
show();
break;
case 4:
set(s);
break;
case 5:
System.out.println("Finally there are " + counter + " items available.");
break;
}
}
else
System.out.println("Error. Number must be between 1 and 5.");
}
Your program is throwing an exception because you told it to:您的程序抛出异常是因为您告诉它:
throw new IllegalArgumentException();
If you want it to loop back to the top, just don't do anything in the default
case!如果你想让它循环回到顶部,在default
情况下不要做任何事情! You can delete the whole default
case all together.您可以一起删除整个default
情况。
The other thing you need to do is to actually read the input that you failed to read.您需要做的另一件事是实际读取您未能读取的输入。 Also, you should reset topChoice
back to 0, otherwise it will end up doing whatever it did last time the loop ran.此外,您应该将topChoice
重置为 0,否则它将最终执行上次循环运行时所做的任何事情。
try {
topChoice = Integer.parseInt(s.next("[1-5]"));
} catch (InputMismatchException e) {
System.out.println("You need to enter an integer between 1-5.");
s.nextLine(); // <----- here
topChoice = 0; // <---- and here
}
Otherwise in the next iteration of the loop, the scanner is going to try to read the same input that it couldn't read before, and fail again, creating an infinite loop.否则,在循环的下一次迭代中,扫描器将尝试读取之前无法读取的相同输入,然后再次失败,从而创建无限循环。
Even though the code works after the modifications above, you shouldn't really do "control flow" with exceptions.即使代码在上面的修改之后工作,你不应该真的做“控制流”有异常。 You should read a line, then check whether it matches a pattern:您应该阅读一行,然后检查它是否与模式匹配:
String line = s.nextLine();
if (line.matches("[1-5]")) {
topChoice = Integer.parseInt(line);
} else {
System.out.println("You need to enter an integer between 1-5.");
topChoice = 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.