简体   繁体   English

JAVA:异常处理有问题吗? 程序仅捕获一次异常

[英]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 -> 489 -> 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.

相关问题 Java:独立的主逻辑和异常处理逻辑 - Java: separate main logic & exception-handling logic 异常处理在运行程序中只能运行一次 - Exception Handling works only once in running program 异常处理方法没有完成就退出 - exception-handling method exit without finishing 为什么Java的异常处理语句不应被视为非本地分支的一般机制? - Why Java’s exception-handling statements should not be considered a general mechanism for nonlocal branching? 使用线程/通知父线程有关 Java 错误的异常处理的最佳实践解决方案 - Best-practice solution for exception-handling using threads/notifying parent thread about error in Java 在 Spring Boot 中的异常处理期间保留自定义 MDC 属性 - Preserve custom MDC attributes during exception-handling in Spring Boot 即使程序捕获异常,仍继续执行 - Continue Execution even after program catches exception Java输入异常处理的一些问题 - A few problems with java input exception handling (Java)GUI NumberFormatException捕获异常,但挂起了窗口 - (Java) GUI NumberFormatException catches exception, but hangs the window 在Java中捕获异常的并发排序任务执行器 - Concurrent sorted task executor that catches Exception in Java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM