javastringcharstring-matchingdigits

Check if character is not a digit


In my program, I need to check and see if characters are certain index's are digits. The condition I have set checks and decides if it's a digit

// Check to make sure all other characters are digits
if (Character.isDigit(militaryTime.charAt(0))) {
    System.out.println(militaryTime + " is not a valid miliary time.");
} else if (Character.isDigit(militaryTime.charAt(1))) {
    System.out.println(militaryTime + " is not a valid miliary time.");
} else if (Character.isDigit(militaryTime.charAt(3))) {
    System.out.println(militaryTime + " is not a valid miliary time.");
} else if (Character.isDigit(militaryTime.charAt(4))) {
    System.out.println(militaryTime + " is not a valid miliary time.");
}

However, I realized the problem when I run it, it says that times that are supposed to be valid, aren't. That's when I realized, it's checking to see if the index is a digit and if so it's returning that the time isn't valid.

How can I make it so that it checks if it is NOT a digit and thus displays the incorrect output, else it just moves on? I tried isLetter, but that just crashed my program.


Solution

  • Use

    if (!Character.isDigit(whatever))
    

    And if you want something really simple to use - use a regular expression: ^\d{4}$ is the regexp for exactly four digits.

    Update: to catch invalid hours, you'll need a more complicated regexp. ^([01]\d\d\d|2[0-3]\d\d)$, or use Javas SimpleDateFormat.