Search code examples
javatypeserror-handlingthrow

Checking if input is correct type java


    System.out.println("What letter should the word begin with?");
        char letter = input.next().charAt(0);
        if(letter != ''){
            throw new InputMismatchException("Please input a letter");
        }

I want to check to see if the user input anything besides a string/char. If they have I want to throw an exception that says the input is wrong. This is my current code but as it stands it does not compile.


Solution

  • You can check whether letter is a letter like this:

    if ((letter >= 'A' && letter <= 'Z') || (letter >= 'a' && letter <= 'z'))
    

    Actually, Scanner has this handy overload of next(String pattern) that throws an InputMismatchException automatically if the input does not match a pattern:

    char letter = input.next("[a-zA-Z]").charAt(0);
    

    [a-zA-Z] is the pattern used here. It accepts any character from a to z or from A to Z.