Search code examples
javacharacterisnull

What is the best Java 8 Character method for detecting no character?


I've got a simple program, written in Java, and I am trying to find a way to validate that anything at all has been entered before the user hits "enter" in the console. Currently, I'm using isLetter() to ensure that a letter has been entered, but this doesn't seem to prevent someone from entering nothing and hitting enter. I've tried several methods in the documentation, and can't seem to locate one that works.

For the snippet below, I'm showing how I've successfully censured that the input variable "letter" is a single character, and will always be a single character, but this doesn't prevent a user from hitting "enter" after typing nothing.

 if (! Character.isLetter(letter)) {  //Don't forget to validate for no chars entered!
      throw new IllegalArgumentException("A letter is required");

Solution

  • Since you're using a readLine() call, and typically, readLine() calls don't include the line termination characters in the return value, why don't you just do:

    if (!yourInput.equals("")) {/* code */}
    

    In fact, you can put that even before you try to charAt(0)