• Register
40 views

Hi, I am new to this world of programming in java language. You might feel to check if a character is a number in java? I mean what is the best way to do it?

Solution:

I'm not sure if this is the best option or not, But this seems pretty simple to me. We can check whether the given character is a number or not by using the isDigit() method of Character class. This method returns true if the passed character is really a digit.

Please check out the example below:

public class CharacterCheck {
   public static void main(String[] args) {
      String s = "ABC123";
      for(int Count=0; Count < s.length(); Count++) {
         Boolean ReturnValue = Character.isDigit(s.charAt(Count));
         if(ReturnValue) {
            System.out.println("'"+ s.charAt(Count)+"' = Num");
         }
         else {
            System.out.println("'"+ s.charAt(Count)+"' = NAN");
         }
      }
   }
}

Please check out the result of the code:

'A' = NAN
'B' = NAN
'C' = NAN
'1' = Num
'2' = Num
'3' = Num

I hope this might help you.

posted Mar 18 in java by (5,970 points)  
edited Mar 18 by

Hi, I'm not sure if this is the best option or not, But this seems pretty simple to me. We can check whether the given character is a number or not by using the isDigit() method of Character class. This method returns true, if the passed character is really a digit.

Please check out the example below:

public class CharacterCheck {
   public static void main(String[] args) {
      String s = "ABC123";
      for(int Count=0; Count < s.length(); Count++) {
         Boolean ReturnValue = Character.isDigit(s.charAt(Count));
         if(ReturnValue) {
            System.out.println("'"+ s.charAt(Count)+"' = Num");
         }
         else {
            System.out.println("'"+ s.charAt(Count)+"' = NAN");
         }
      }
   }
}

Please check out the result of the code:

'A' = NAN
'B' = NAN
'C' = NAN
'1' = Num
'2' = Num
'3' = Num

I hope you got the answer.

...