61

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.");
MByD
  • 135,866
  • 28
  • 264
  • 277
user1701604
  • 985
  • 4
  • 11
  • 15

12 Answers12

76

You could use:

    if (Character.isLetter(character.charAt(0))){
    ....
Reimeus
  • 158,255
  • 15
  • 216
  • 276
27

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.

Hristo
  • 45,559
  • 65
  • 163
  • 230
16

Ummm, you guys are forgetting the Character.isLetterOrDigit method:

boolean x;
String character = in.next();
char c = character.charAt(0);
if(Character.isLetterOrDigit(charAt(c)))
{ 
  x = true;
}
Nick Roth
  • 3,057
  • 2
  • 15
  • 15
Fluffle
  • 181
  • 1
  • 7
7

This is a little tricky, the value you enter at keyboard, is a String value, so you have to pitch the first character with method line.chartAt(0) where, 0 is the index of the first character, and store this value in a char variable as in char c= line.charAt(0) now with the use of method isDigit() and isLetter() from class Character you can differentiate between a Digit and Letter.

here is a code for your program:

import java.util.Scanner;

class Practice
{
 public static void main(String[] args)
  {
   Scanner in = new Scanner(System.in);
   System.out.println("Input a letter"); 
   String line = in.nextLine();
   char c = line.charAt(0);
   if( Character.isDigit(c))
   System.out.println(c +" Is a digit");
   else if (Character.isLetter(c))
   System.out.println(c +" Is a Letter");
  }

}
Idriss Neumann
  • 3,760
  • 2
  • 23
  • 32
Brainiac Khan
  • 93
  • 1
  • 7
6

By using regular expressions:

boolean isChar = character.matches("[a-zA-z]{1}");
boolean isDigit = character.matches("\\d{1}"); 
Michael
  • 1,347
  • 1
  • 13
  • 27
4
char charInt=character.charAt(0);   
if(charInt>=48 && charInt<=57){
    System.out.println("not character");
}
else
    System.out.println("Character");

Look for ASCII table to see how the int value are hardcoded .

Baz
  • 36,440
  • 11
  • 68
  • 94
Jimmy
  • 2,589
  • 21
  • 31
  • @vandey.. Why would you want to re-invent the wheel?? There already pre-defined method to do this task for you.. – Rohit Jain Oct 03 '12 at 19:26
  • 1
    It is just that if the OP wants to learn, he can understand what actually is going on when he calls those method. – Jimmy Oct 03 '12 at 19:29
  • @RohitJain, `Character.isDigit` cheks for digit in **any** digit system, and this solution will ignore anything except arabic digits – msangel May 30 '14 at 16:52
3

This is the way how to check whether a given character is alphabet or not

public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);
    char c = sc.next().charAt(0); 
    if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
         System.out.println(c + " is an alphabet.");
    else
        System.out.println(c + " is not an alphabet.");
}
Rajat Jain
  • 1,339
  • 2
  • 16
  • 29
malith vitha
  • 473
  • 4
  • 4
2
     char temp = yourString.charAt(0);
     if(Character.isDigit(temp))
     {
         ..........
     }else if (Character.isLetter(temp))
     {
          ......
      }else
     {
      ....
     }
kosa
  • 65,990
  • 13
  • 130
  • 167
2
import java.util.*;

public class String_char 
{

    public static void main(String arg[]){   

        Scanner in = new Scanner(System.in);
        System.out.println("Enter the value");
        String data;
        data = in.next();

        int len = data.length();
        for (int i = 0 ; i < len ; i++){
            char ch = data.charAt(i);

            if ((ch >= '0' && ch <= '9')){
                System.out.println("Number ");
            }
            else if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')){
            System.out.println("Character");
            }
            else{
                System.out.println("Symbol");
             }
        }
    } 
}
KarelG
  • 5,176
  • 4
  • 33
  • 49
  • 1
    While this code snippet may solve the question, [including an explanation](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – DimaSan Mar 15 '17 at 11:26
1

You need to convert your string into character..

String character = in.next();
char myChar = character.charAt(0);

if (Character.isDigit(myChar)) {
   // print true
}

Check Character for other methods..

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
1

You could do this by Regular Expression as follows you could use this code

EditText et = (EditText) findViewById(R.id.editText);
String NumberPattern = "[0-9]+";
String Number = et.getText().toString();

if (Number.matches(NumberPattern) && s.length() > 0)
{ 
    //code for number
}
else
{
    //code for incorrect number pattern
}
Jeffy
  • 276
  • 3
  • 9
0

I have coded a sample program that checks if a string contains a number in it! I guess it will serve for this purpose as well.

public class test {
    public static void main(String[] args) {
        String c;
        boolean b;

        System.out.println("Enter the value");
        Scanner s = new Scanner(System.in);
        c = s.next();
        b = containsNumber(c);
        try {
            if (b == true) {
                throw new CharacterFormatException();
            } else {
                System.out.println("Valid String \t" + c);
            }
        } catch (CharacterFormatException ex) {
            System.out.println("Exception Raised-Contains Number");

        }
    }

    static boolean containsNumber(String c) {
        char[] ch = new char[10];
        ch = c.toCharArray();

        for (int i = 0; i < ch.length; i++) {
            if ((ch[i] >= 48) && (ch[i] <= 57)) {
                return true;
            }
        }
        return false;
    }
}

CharacterFormatException is a user defined Exception. Suggest me if any changes can be made.

Tom
  • 16,842
  • 17
  • 45
  • 54
Max
  • 1