Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a character in a string is a digit or letter

Tags:

java

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."); 
like image 264
user1701604 Avatar asked Oct 03 '12 19:10

user1701604


People also ask

How do you check if each character in a string is a digit?

Python String isdigit() The isdigit() method returns True if all characters in a string are digits.

How do you check if a character in a string is a digit or letter Python?

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 .

How do you check if a character in a string is a letter?

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.


2 Answers

You could use:

    if (Character.isLetter(character.charAt(0))){     .... 
like image 86
Reimeus Avatar answered Sep 29 '22 23:09

Reimeus


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.

like image 33
Hristo Avatar answered Sep 30 '22 00:09

Hristo