import java.util.InputMismatchException;
import java.util.Scanner;
public class array
{
public static void main(String[] args)
{
int marks=0;
Scanner input = new Scanner(System.in);
int array[] = new int[5];
System.out.println("Please enter the marks of students one by one");
for(int i = 0;i < array.length;i++)
{
try
{
marks = input.nextInt();
}
catch(InputMismatchException e)
{
System.out.println(e);
System.out.println("Please enter an integer value");
}
array[i]=marks;
}
System.out.println("index Value" );
for(int i=0;i<array.length;i++)
{
System.out.println(" "+i+" "+array[i]);
}
}
}
Above is my code. I tried to catch the exception of the user typing any other data other than integer value and its working fine as it is catching the exception. But the problem is that it is not giving control back to the user. You will understand it better with the output. Following is message i am getting while execution. It is text copied from command prompt.
Please enter the marks of students one by one
abc
java.util.InputMismatchException
Please enter an integer value
java.util.InputMismatchException
Please enter an integer value
java.util.InputMismatchException
Please enter an integer value
java.util.InputMismatchException
Please enter an integer value
java.util.InputMismatchException
Please enter an integer value
index Value
0 0
1 0
2 0
3 0
4 0
As you could see as i entered 'abc' as input it catched the exception and gave out the proper message but it did it for 5 times i.e. size of my array.
Why is it not giving the control back to user?