[Java] Java判断一个字符是否是数字的几种方法 →→→→→进入此内容的聊天室

来自 , 2019-06-22, 写在 Java, 查看 99 次.
URL http://www.code666.cn/view/210192ab
  1. // 如何判断一个字符是数字
  2. public class Test
  3. {
  4.     /* 测试函数 */
  5.     public static void main(String[] args)
  6.     {
  7.         char[] ch =
  8.         {
  9.                 'a', '1', 'b', '2', 'c', '3', 'd', '4',
  10.         };
  11.         System.out.println(ch[0] + ": " + isDigitA(ch[0]));
  12.         System.out.println(ch[1] + ": " + isDigitA(ch[1]));
  13.         System.out.println(ch[2] + ": " + isDigitB(ch[2]));
  14.         System.out.println(ch[3] + ": " + isDigitB(ch[3]));
  15.         System.out.println(ch[4] + ": " + isDigitC(ch[4]));
  16.         System.out.println(ch[5] + ": " + isDigitC(ch[5]));
  17.         System.out.println(ch[6] + ": " + isDigitD(ch[6]));
  18.         System.out.println(ch[7] + ": " + isDigitD(ch[7]));
  19.     }
  20.  
  21.     /* 1.用JAVA自带的函数 */
  22.     private static boolean isDigitA(char ch)
  23.     {
  24.         return Character.isDigit(ch);
  25.     }
  26.  
  27.     /* 2.用正则表达式 */
  28.     private static boolean isDigitB(char ch)
  29.     {
  30.         Pattern pattern = Pattern.compile("[0-9]");
  31.         return pattern.matcher(String.valueOf(ch)).matches();
  32.     }
  33.  
  34.     /* 3.用ascii码 */
  35.     private static boolean isDigitC(char ch)
  36.     {
  37.         if (ch < 48 || ch > 57)
  38.             return false;
  39.         else
  40.             return true;
  41.     }
  42.  
  43.     /* 4.强制类型转化是否抛出异常来判断 */
  44.     private static boolean isDigitD(char ch)
  45.     {
  46.         try
  47.         {
  48.             int i = Integer.parseInt(String.valueOf(ch));
  49.             return true;
  50.         }
  51.         catch (NumberFormatException e)
  52.         {
  53.             e.printStackTrace();
  54.             return false;
  55.         }
  56.  
  57.     }
  58. }
  59. //java/6690

回复 "Java判断一个字符是否是数字的几种方法"

这儿你可以回复上面这条便签

captcha