How to reject characters/ letters in a java program

935 views Asked by At

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

There are 2 answers

2
Spectric On BEST ANSWER

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

0
WJS On

Try the following: You need to catch the input mismatch and then continue taking input. It is important to update the loop counter to allow for all 10 inputs to be taken.

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++) {
        try {
           Array[i] = input.nextInt();
        } catch(InputMismatchException ie) {
            System.out.println("Bad input - please re-enter");
            i--; // update loop;
            input.nextLine();// clear bad input from buffer scanner.
        }
     }

   System.out.print("Enter an index you want to retrieve: ");
   index = input.nextInt();

   System.out.print("Element at index "+index+" is " + Array[index]);