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");
}
}
}
}
Output
'A' = NAN
'B' = NAN
'C' = NAN
'1' = Num
'2' = Num
'3' = Num
Also there is alternatine method, read alternative
Top comments (1)
Arrays.stream(s.charArray()).forEach(c -> System.out.println(c + " " + Character.isDigit(c)));
This is just to do exactly what you did in your example. Depending on what you're doing with the result, you might want to use a different method.