77.0k views
4 votes
Write a program that prompts the user to read two integers and displays their sum . if anything but an integer is passed as input, your program should catch the inputmismatchexception that is thrown and prompt the user to input another number by printing "please enter an integer ."

User Eckstein
by
7.4k points

1 Answer

4 votes
The Java code below will ask for two integers and display the sum. If a non-integer is submitted the code will ask again. The break is used to exit the while true loop indicating that no-errors had occurred and two numbers were added. System.out.print("Please insert two integers and this will display the sum."); int numOne; int numTwo; while (True) { try{ System.out.print("Integer Number One? "); numOne = input.nextInt(); System.out.print("Integer Number Two? "); numTwo = input.nextInt(); System.out.print("The Sum Is: " + (numOne + numTwo)); break; } catch (InputMismatchException e) { System.out.print("please enter an integer ."); } }
User Randomstatistic
by
7.1k points