1
    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.

9
  • 5
    Everything the user can enter is a char. There's no way to enter anything other than chars. You need to tell us what your definition of char is. But, have you at least read the javadoc of java.lang.Character? Commented Apr 14, 2018 at 14:21
  • What is the overall goal of your program? Commented Apr 14, 2018 at 14:21
  • Every input can be interpreted as a char because every character, every number and every punctuation sign it's an ascii character. You must tell whats the goal of the program to can give you some advice as @TimBiegeleisen said. Commented Apr 14, 2018 at 14:29
  • @J.Lorenzo actually, most of them are not ASCII characters. ASCII only support 127 characters. Commented Apr 14, 2018 at 14:31
  • 1
    So, you want the user to enter a letter between 'A' and 'Z'. That's not the same thing as a char. '1' is a char. 'é' is a char. '😊' is a char. So you want if (letter >= 'A' && letter <= 'Z'). Commented Apr 14, 2018 at 14:59

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much! I have fixed the issue!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.