Reputation: 5
public static void main(String[] args) {
// TODO Auto-generated method stub
char c;
do {
Scanner s=new Scanner(System.in);
try {
int size=s.nextInt();
int[] arr=new int[size];
for(int i=0;i<size;i++) {
arr[i]=s.nextInt();
}
bubblesort(arr);
for(int i=0;i<arr.length;i++) {
System.out.print(arr[i]+" ");
}
System.out.println();
} catch(Exception e) {
System.out.println("Invalid Input");
} finally {
System.out.println("Want to repeat(y/n)");
System.out.println(s);
c=s.next().charAt(0);
}
} while(c=='y' || c=='Y');
}
When I am giving valid input then after performing sorting it also takes input character c inside finally block, but when i give invalid input then after going to catch block it only prints the output inside finally block but doesn't take input character c. Why is it happening so?
Upvotes: 0
Views: 140
Reputation: 3236
Probably this happens because your scanner does not advance after receiving invalid input. According to official documentation of Scanner:
public int nextInt(int radix)
Scans the next token of the input as an int. This method will throw InputMismatchException if the next token cannot be translated into a valid int value as described below. If the translation is successful, the scanner advances past the input that matched.
And also:
When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.
Therefore your scanner will never go past nextInt
and reach the execution of next()
Upvotes: 4