When the program asks the user to input 10 elements (numbers), but the user entered any letter or word, I want the program to display "INVALID INPUT". I tried an if statement but it doesn't work. Any help is much appreciated!
This is my code:
int [] Array = new int[10];
int index;
Scanner input = new Scanner(System.in);
System.out.println("Enter 10 elements:");
for (int i = 0; i < 10; i++) {
Array[i] = input.nextInt();
}
System.out.print("Enter an index you want to retrieve: ");
index = input.nextInt();
System.out.print("Element at index "+index+" is " + Array[index]);
}
}
You can use a
try-catch
and catch aInputMismatchException
, where you can then handle it accordingly.Like so:
For example, when I input:
I get:
Because spectric is cool