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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…