javaprintfinvalid-characters

How to reject characters/ letters in a java program


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!

enter image description here

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]);
    }
}

Solution

  • You can use a try-catch and catch a InputMismatchException, where you can then handle it accordingly.

    Like so:

        try{
           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]);
        }catch(InputMismatchException e){
            System.out.println("INVALID INPUT");
        }
    

    For example, when I input:

    spectric is not cool
    

    I get:

    INVALID INPUT
    

    Because spectric is cool