Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
168 views
in Technique[技术] by (71.8m points)

Handling Exception Errors through try-catch

I've taught myself how to write basic code, and now I'm trying to teach myself more about exception handling and how it all works. Though, I'm having a few problems with it all. A little help would be more than appreciated!

I'm using a Try-Catch block inside a Do-While loop in order to read in two integers and display the sum. I've tried several different ways to try and get this to work, though, I've not had much luck. My code is:

public static void main(String[] args) {
Scanner in = new Scanner(System.in);
boolean continueInput = true;
    
do {
    try{
        System.out.print("Enter first integer: ");
        int number1 = in.nextInt();
    
        continueInput = false;
    }
    catch (InputMismatchException ex) {
        System.out.println("Try again. (Incorrect input: an integer is required)");
        in.nextLine();
    }
            
    }while (continueInput);
    
do {
    try{
        System.out.print("Enter second integer: ");
        int number2 = in.nextInt();
            
        continueInput = false;
    }
    catch (InputMismatchException ex) {
            System.out.println("Try again. (Incorrect input: an integer is required)");
        in.nextLine();
    }
            
    }while (continueInput);
    
System.out.println("The sum is " + (number1 + number2));
}

Is there a way to include both integers within a single Do-While? Also, the IDE is not recognizing my variables "number1" and "number2" - is this because they are declared within the loop?

question from:https://stackoverflow.com/questions/65832976/handling-exception-errors-through-try-catch

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This may not be very pythonesque but Id just make a little function to give the prompt and validiate and return the result; then have a single do{}while loop with two calls to it. (Id like to include code fragments but I seem to have an issue posting code blocks)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...