I have the user entering a single character into the program and it is stored as a string. I would like to know how I could check to see if the character that was entered is a letter or a digit. I have an if statement, so if its a letter its prints that it's a letter, and the same for a digit. The code I have so far doesn't work but I feel like I'm close. Any help you can offer is appreciated.
System.out.println("Please enter a single character: "); String character = in.next(); System.out.println(character); if (character.isLetter()){ System.out.println("The character entered is a letter."); } else (character.isDigit()){ Syste.out.println("The character entered is a digit.");
Python String isdigit() The isdigit() method returns True if all characters in a string are digits.
isalnum() is a built-in Python function that checks whether all characters in a string are alphanumeric. In other words, isalnum() checks whether a string contains only letters or numbers or both. If all characters are alphanumeric, isalnum() returns the value True ; otherwise, the method returns the value False .
You can use the Character. isLetter(char c) method to check if a character is a valid letter. This method will return a true value for a valid letter characters and false if the character is not a valid letter.
You could use:
if (Character.isLetter(character.charAt(0))){ ....
You could use the existing methods from the Character class. Take a look at the docs:
http://download.java.net/jdk7/archive/b123/docs/api/java/lang/Character.html#isDigit(char)
So, you could do something like this...
String character = in.next(); char c = character.charAt(0); ... if (Character.isDigit(c)) { ... } else if (Character.isLetter(c)) { ... } ...
If you ever want to know exactly how this is implemented, you could always look at the Java source code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With