Problem with exception handling
Am writing a code to display the sum of 16 numbers taken from user. The program is supposed to print error message, if user input an invalid integer and then let the user to enter that int again, my code is:
Code:
Scanner sc=new Scanner(System.in);
int sum=0;
for(int i=0; i<16; i++){
System.out.printf("Enter number of rotations for round No %d:\t", i+1);
try{
sum += sc.nextInt();
}catch(Exception e){
System.out.printf("\nSorry! invalid number! Enter number again \n");
i--;
}
}
System.out.println(sum);
The problem is when I enter an invalid integer, program displays error message and than automatically take that same input in next cycle, without letting user to give input. this result in infinite loop displaying error messages on each cycle
Their is sample program output
Code:
Enter number 1: a
Sorry! invalid number! Enter number again
Enter number 1:
Sorry! invalid number! Enter number again
Enter number 1:
Sorry! invalid number! Enter number again
Enter number 1:
Sorry! invalid number! Enter number again
Enter number 1:
Sorry! invalid number! Enter number again
Enter number 1:
Sorry! invalid number! Enter number again
Enter number 1:
Sorry! invalid number! Enter number again
Enter number 1:
Sorry! invalid number! Enter number again
....................
Please help where am wrong :(
Re: Problem with exception handling
- Don't modify the loop index (i in your program), from within the loop -- it's a recipe for disaster.
- Instead use a while loop inside of your for loop, and change the while condition that allows one to exit the while loop after the user's input has been validated. If the validation fails, that line is never reached and the condition won't be changed until valid input is entered.
- Using a Scanner's nextInt() can be tricky as it does not handle the end of line token very well. If you must use this rather than nextLine() and then Integer.parseInt(...), consider placing sc.nextLine(); in a finally {} block after the catch block.
Re: Problem with exception handling
This is a little safe integer method I wrote for a lab.
It should help you out a bit without giving away the answer completely.
Code:
public int safeInt(String message)
{
int input=0;
System.out.println(message);
boolean badInput=true;
while(badInput){
try{
input=scan.nextInt();
badInput=false;
}
catch(InputMismatchException e)
{
System.out.println("That input was not possible.\n please try again.");
scan.nextLine();
}
}
return input;
}
Re: Problem with exception handling
Thnx Fubarable, problem is solved now :)
Thnx popeus, I learned some new things from you :)