import java.util.*; // for Scanner /* This program will attempt to input 2 int values and sum them. An exception is thrown by the JVM if the user does not * input the correct type (ints because of s.nextInt()). The catch block will output the exception and tell the user * to try again. The boolean correct is used to determine whether to repeat the loop or not, in this way we can repeat * until the user gets it right! Note that we must declare the Scanner inside the try block or else, for some reason, * the original input values continue to be used and we get into an infinite loop of having the same exception thrown * over and over */ public class Ch14_2 { public static void main(String[] args) { boolean correct=false; // repeat until the user gets the input correct while(!correct) { try { Scanner s=new Scanner(System.in); int x, y,sum=0; System.out.println("Enter two integer values one at a time and I will sum them up"); x=s.nextInt(); // we expect 2 int values, any other type will thrown an InputMismatchException y=s.nextInt(); sum=x+y; // under normal circumstances, we reach here to compute the sum, output the result correct=true; // and since we got proper input, we set correct to true to exit the while loop System.out.println(sum); } catch(InputMismatchException e) // if the exception is thrown, transfer control here { // but notice that the program will then terminate without outputting a sum - see below System.out.println(e); System.out.println("Your numbers were incorrect, try again"); } } } }