检查字符串是否在Java中仅包含Unicode数字
为了检查Java中的String是否只有unicode数字,我们使用带有决策语句的isDigit()方法和charAt()方法。
isDigit(intcodePoint)方法确定特定字符(UnicodecodePoint)是否为数字。它返回一个布尔值,为true或false。
声明-java.lang.Character.isDigit()方法的声明如下-
public static boolean isDigit(int codePoint)
其中参数codePoint代表要检查的字符。
该charAt()方法返回给定索引处的字符值。它属于Java中的String类。索引必须在0到length()-1之间。
声明-java.lang.String.charAt()方法的声明如下-
public char charAt(int index)
让我们看一个检查Java中的String是否只有unicode数字的程序。
示例
public class Example {
   boolean check(String s) {
      if (s == null) // checks if the String is null {
         return false;
      }
      int len = s.length();
      for (int i = 0; i < len; i++) {
         //检查字符是否不是数字
         if ((Character.isDigit(s.charAt(i)) == false) ) {
            return false; // if it is not a digit then it will return false
         }
      }
      return true;
   }
   public static void main(String [] args) {
      Example e = new Example();
      String s = "1024"; // has only unicode digits so it will return true
      String s1 = "13f4"; // has digits as well as so it will return false
      System.out.println("String "+s+" has only unicode digits : "+e.check(s));
      System.out.println("String "+s1+" has only unicode digits : "+e.check(s1));
   }
}输出结果
String 1024 has only unicode digits : true String 13f4 has only unicode digits : false