[英]JAVA: Problems with Exception-Handling? Program only catches Exception once
I'm attempting to create a program where the user enters a five-digit zip code from 00000 to 99999 and if the user enters a number out of that range or non-numeric values, it should throw an exception and give the user a chance to keep trying until they enter 5 numeric values. 我正在尝试创建一个程序,在该程序中,用户输入从00000到99999的五位数邮政编码,如果用户输入的数字超出该范围或非数字值,它将引发异常并为用户提供机会继续尝试直到他们输入5个数字值。
My program only seems to catch the first instance of it, and afterwards it simply prints out the 2nd thing the user enters even if it doesn't fit the requirements. 我的程序似乎只捕获了它的第一个实例,然后即使它不符合要求,它也只是打印出用户输入的第二个东西。
I've just been stumped, and I'm not sure how I can use a while loop with my code, though I believe that's what I may need maybe? 我刚刚感到难过,我不确定如何在代码中使用while循环,尽管我认为那也许是我需要的?
I'm a beginner at this and any help would be appreciated! 我是这个的初学者,任何帮助将不胜感激!
import java.util.InputMismatchException;
import java.util.Scanner;
public class xzip_code {
public static void main(String[] args)
{
try
{
Bounds(Program());
}
catch(IllegalArgumentException ex)
{
System.out.println("Enter 5 Digits");
Program();
}
catch(InputMismatchException ex)
{
System.out.println("Enter Numbers");
Program();
}
}
public static void Bounds(String answer)
{
int length = answer.length();
if(length<5 || length>5)
{
throw new IllegalArgumentException("Enter 5 Digits");
}
char a = answer.charAt(0);
char b = answer.charAt(1);
char c = answer.charAt(2);
char d = answer.charAt(3);
char e = answer.charAt(4);
int f = a;
int g = b;
int h = c;
int i = d;
int j = e;
if(f>58 || g>58 || h>58|| i>58||j>58)
{
throw new InputMismatchException("Enter Numbers");
}
}
public static String Program()
{
Scanner userInput = new Scanner(System.in);
String x = userInput.next();
System.out.println(x);
return x;
}
}
Your method Bounds()
does the validation work. 您的方法
Bounds()
完成验证工作。
Currently, in your catch block you are just calling Program()
. 当前,在catch块中,您只是在调用
Program()
。 Instead you need to call the Bounds()
and pass parameter Program()
to it. 相反,您需要调用
Bounds()
并将参数Program()
传递给它。
The below code will loop until there is no exception (successful try block execution). 下面的代码将循环直到没有异常(成功执行try块)。
boolean flag = true;
while(flag) {
try {
Bounds(Program());
flag = false;
} catch(IllegalArgumentException ex) {
System.out.println("Enter 5 Digits");
}
catch(InputMismatchException ex) {
System.out.println("Enter Numbers");
}
}
You also need to check if user has entered only numbers. 您还需要检查用户是否仅输入数字。
ASCII value of 0 -> 48
and 9 -> 57
. ASCII值
0 -> 48
和9 -> 57
。 Therefore, your check of > 58
makes no sense. 因此,检查
> 58
毫无意义。 It should check within the range. 它应检查在范围内。
You can simple use if (Character.isLetter(answer.charAt(index)))
to check for individual digits (which is tedious). 您可以简单地使用
if (Character.isLetter(answer.charAt(index)))
检查单个数字(这很乏味)。
Instead, just convert the String to Integer and check if it successfully gets converted otherwise throw error. 相反,只需将String转换为Integer并检查其是否成功转换,否则抛出错误。
try {
Integer.parseInt(answer);
} catch (NumberFormatException e) {
throw new InputMismatchException("Enter Numbers");
}
You need to make your catch a recursive call. 您需要使catch成为递归调用。 The way you wrote it, it is caught, tries again, then ends.
您编写它的方式被捕获,然后重试,然后结束。
Try to do it like this. 尝试这样做。
void foo() {
try {
bar();
} catch (Exception e) {
// try again
foo();
}
}
It also may be a good idea to keep track of how many times you retry. 跟踪重试多少次也是一个好主意。 This could easily cause a
StackOverflowError
if you get it wrong too many times. 如果您多次错误将很容易导致
StackOverflowError
。 I want to say the number is about 8 or 9 thousand. 我想说这个数字大约是8或9000。
Another option would be to use a loop. 另一种选择是使用循环。
void foo() {
boolean success = false;
while(!success) {
success = tryFoo();
}
}
boolean tryFoo() {
try {
bar();
return true; // true for success
} catch (Exception e) {
return false; // false for failed
}
}
You need to call Bounds(Program());
您需要调用
Bounds(Program());
untill your program throws no error. 直到程序没有错误。 For that I created
while
loop that verifies if boolean isError
is true. 为此,我创建了
while
循环,用于验证boolean isError
是否为true。 To check if entered char is digit you can use Character.isDigit
method. 要检查输入的字符是否为数字,可以使用
Character.isDigit
方法。 See correct code: 查看正确的代码:
package com.stackoverflow.main;
import java.util.InputMismatchException;
import java.util.Scanner;
public class xzip_code {
public static void main(String[] args) {
System.out.println("Enter 5 Digits");
boolean isError = true;
while (isError) {
try {
Bounds(Program());
} catch (IllegalArgumentException ex) {
System.out.println("Enter 5 Digits");
continue;
} catch (InputMismatchException ex) {
System.out.println("Enter Numbers");
continue;
}
isError = false;
}
}
public static void Bounds(String answer) {
int length = answer.length();
if (length < 5 || length > 5) {
throw new IllegalArgumentException("Enter 5 Digits");
}
char a = answer.charAt(0);
char b = answer.charAt(1);
char c = answer.charAt(2);
char d = answer.charAt(3);
char e = answer.charAt(4);
if (!(Character.isDigit(a) && Character.isDigit(b) && Character.isDigit(c) && Character.isDigit(d)
&& Character.isDigit(e))) {
throw new InputMismatchException("Enter Numbers");
}
}
public static String Program() {
Scanner userInput = new Scanner(System.in);
String x = userInput.next();
System.out.println(x);
return x;
}
}
Prints: 印刷品:
Enter 5 Digits
ewewdsddd
ewewdsddd
Enter 5 Digits
dffdffg
dffdffg
Enter 5 Digits
443446665
443446665
Enter 5 Digits
4444q
4444q
Enter Numbers
33333
33333
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.