why does my code throws exception without taking a single input??
import java.util.*;
public class program3{
public static void main(String[] args) {
System.out.println("Enter the number of elements in the array");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
try{
System.out.println("Enter the elements in the array");
for(int i=0;i<n;i++){
String j = sc.nextLine();
int k = Integer.parseInt(j);
arr[i]=k;
}
System.out.println("Enter the index of the array element you want to access");
int a = sc.nextInt();
System.out.println("The array element at index "+a+" = "+arr[a]);
System.out.println("The array element successfully accessed");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println(e);
}
catch(NumberFormatException e){
System.out.println(e);
}
}
}
I need to generate NumberFormatException when I provide an input other than int. Instead, it is generated without taking any input.
This is the error message
Enter the number of elements in the array
2
Enter the elements in the array
java.lang.NumberFormatException: For input string: ""