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");
}
}
}
}
Enter fullscreen mode Exit fullscreen mode
Output
'A' = NAN
'B' = NAN
'C' = NAN
'1' = Num
'2' = Num
'3' = Num
Enter fullscreen mode Exit fullscreen mode
Also there is alternatine method, read alternative
© 版权声明
THE END
暂无评论内容