Java如何检查字符是否代表数字?

为了进行验证,我们可能需要检查用户输入的数据是否是可供我们处理的有效数据。可以通过使用java.lang.CharacterclassisDigit(char c)方法来完成检查输入的字符是否为数字的简单机制。

在此示例中,您将学习如何检查字符是否代表数字。您将首先创建一个包含一些随机字母数字字符的字符串。然后,您将迭代这些字符,使用charAt()方法获得特定位置的值。在上一节中,您将检查字符是否代表数字。

package org.nhooo.example.lang;

public class CharacterIsDigitExample {
    public static void main(String[] args) {
        // 手动创建带有随机字符的字符串。
        String str = "12?ABC4!6def78+HI@0";

        for (int i = 0; i < str.length(); i++) {
            // 确定指定字符是否为数字
            if (Character.isDigit(str.charAt(i))) {
                System.out.println(str.charAt(i) + " is a digit.");
            } else {
                System.out.println(str.charAt(i) + " not a digit.");
            }
        }
    }
}

这些是我们程序的输出:

1 is a digit.
2 is a digit.
? not a digit.
A not a digit.
B not a digit.
C not a digit.
4 is a digit.
! not a digit.
6 is a digit.
d not a digit.
e not a digit.
f not a digit.
7 is a digit.
8 is a digit.
+ not a digit.
H not a digit.
I not a digit.
@ not a digit.
0 is a digit.