I'm trying to handle an exception but I receive something else. I dont know why I receive this.
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at P4.main(P4.java:28)
I want to handle ArrayOutOfBoundsException. Thank you!
public class P4 {
public static void main(String args[]) {
Scanner keyboard=new Scanner(System.in);
ArrayList <Double> sir = new ArrayList<Double>();
System.out.println("Please insert doubles: ");
do {
double x=keyboard.nextDouble();
sir.add(x);
}while(keyboard.hasNextDouble());
System.out.println("Elements in the array are: " + sir);
System.out.println("Enter the index of the required element: ");
try {
int element = keyboard.nextInt();
System.out.println("Element in the given index is :: "+sir.get(element));
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("The index you have entered is invalid");
}
}
}