I'm doing exercises related to handling exceptions. While using the Scanner class and following exercises to check for InputMismatchExceptions, I got the following results from the following code.
static Scanner sc = new Scanner(System.in);
public static void main(String[] args){
System.out.print("Enter an integer: ");
int a = getInt();
System.out.print("Enter a second integer: ");
int b = getInt();
int result = a + b;
System.out.println(result);
}
public static int getInt(){
while (true){
try {
return sc.nextInt();
}
catch(InputMismatchException e){
System.out.print("I'm sorry, that's not an integer."
+ " Please try again: ");
sc.next();
}
}
}
The output was:
Enter an integer: 2 3
Enter a second integer: 5
It seems that if for the first calling of nextInt() I enter "2 3", or two integers with a space between them, the next time that nextInt() is called, it receives the first two integers added together and then halts the program. What is really going on here?
P.S. Does anyone have tips for me in formatting my code in a better way and making it more organized for other coders to read?