通过trycatch避免inputmismatch
要验证INT输入,我已经看到了使用InputMismatch异常的try-catch的用法。不过,在输入字符串后,我只是播放了捕获代码块,然后由于不匹配而退出程序,但是我想允许用户重新输入输入。搜索后循环时,我在循环时实现了一个布尔值,但这仍然没有解决问题。
int quantity = 0;
boolean correct = true;
while(correct){
try{
System.out.print("Input Quantity you would like to purchase: ");//Get quantity
quantity = input.nextInt();
}catch(InputMismatchException e){
System.out.println("Input must be a number");
input.nextInt();//Get the input as a string
correct = false;
}
System.out.println("Quantity: " + quantity);
}
我以前刚刚使用了扫描仪内置的Hasnextint,它效果很好,但想测试Try-Catch。我听说要使用try-catch而不使用try-catch。为什么我要避免使用它?
To validate for an int input, I've seen the usage of try-catch using the InputMismatch exception. After inputting a string though, I simply get the catch code block played, then my program exits due to mismatch, but instead I want to allow the user to re-enter input. I implemented a boolean correct while loop after searching around but that still didn't do the trick.
int quantity = 0;
boolean correct = true;
while(correct){
try{
System.out.print("Input Quantity you would like to purchase: ");//Get quantity
quantity = input.nextInt();
}catch(InputMismatchException e){
System.out.println("Input must be a number");
input.nextInt();//Get the input as a string
correct = false;
}
System.out.println("Quantity: " + quantity);
}
I previously just used the Scanner's built in hasNextInt, and that works great, but wanted to test out try-catch. I've heard to use try-catch and not to use try-catch. Why would I avoid using it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是修复程序,使用
input.nextline();
在捕获中,并且不要使正确= false,但就像其他指出的那样,尽量不要使用常规流程。仅将其用于跟踪异常例外。因此,我阻止您使用此代码。使用,
input.hasnextint()
而不是Here is the fix, use
input.nextLine();
in catch and don't make the correct=falseBut like others pointed out, try not to use Exceptions for general flow. Use it only for tracking unusual exceptions. So, I am discouraging you to use this code. Use,
input.hasNextInt()
instead