java判断string变量是否是数字

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java判断string变量是否是数字相关的知识,希望对你有一定的参考价值。

1.用正则表达式

首先要import java.util.regex.Pattern 和 java.util.regex.Matcher

/*方法1):推荐,速度最快
  * 利用正则表达式判断字符串是否是数字
  * @param str 传入的字符串 
  * @return 是整数返回true,否则返回false 
 */
    public boolean isNumeric(String str){
           Pattern pattern = Pattern.compile("[0-9]*");
           Matcher isNum = pattern.matcher(str);           
           if( !isNum.matches() ){               
               return false;
           }  return true;
    }
    

/*  2)推荐,速度最快
  * 判断是否为整数 
  * @param str 传入的字符串 
  * @return 是整数返回true,否则返回false 
*/

  public static boolean isInteger(String str) {  
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");  
        return pattern.matcher(str).matches();  
  }

2.用JAVA自带的函数

public static boolean isNumeric(String str)
{
  for (int i = 0; i < str.length(); i++)
  {  
    System.out.println(str.charAt(i));
    if (!Character.isDigit(str.charAt(i)))
    {
        return false;
      }
  }
  return true;
}


3.使用org.apache.commons.lang

org.apache.commons.lang.StringUtils;boolean isNunicodeDigits=StringUtils.isNumeric("aaa123456789");


http://jakarta.apache.org/commons/lang/api-release/index.html下面的解释:public static boolean isNumeric(String str)Checks if the String contains only unicode digits. A decimal point is not a unicode digit and returns false.null will return false. An empty String ("") will return true.

StringUtils.isNumeric(null)   = falseStringUtils.isNumeric("")     = trueStringUtils.isNumeric(" ")   = falseStringUtils.isNumeric("123") = trueStringUtils.isNumeric("12 3") = falseStringUtils.isNumeric("ab2c") = falseStringUtils.isNumeric("12-3") = falseStringUtils.isNumeric("12.3") = false


4、判断ASCII码值

   isNumeric0(String str)
{  
  ( i=str.length();--i>=0;)
  {
      chr=str.charAt(i);
     (chr<48 || chr>57)
         ;
  }
   ;
 }


5、逐个判断str中的字符是否是0-9

   isNumeric3(String str)
{   String number = "0123456789";  ( i = 0;i < number.length; i ++)
  {
(number.indexOf(str.charAt(i)) == -1)
     {  
 ;  
     }  
  }  
   ;
}


6、捕获NumberFormatException异常

   isNumeric00(String str)
{  {
     Integer.parseInt(str);
      ;
  }(NumberFormatException e)
  {
   System.out.println("异常:\"" + str + "\"不是数字/整数...");
    ;
  }
}


本文出自 “Exist” 博客,请务必保留此出处http://exist.blog.51cto.com/10305882/1949627

以上是关于java判断string变量是否是数字的主要内容,如果未能解决你的问题,请参考以下文章

Java判断String类型变量是否可以转换数字类型

java中如何判断两个变量相等

101Java中String类之判断是否由数字组成

如何判断java中一个数据是否一个类的对象

java中判断一个字符串是不是含有子字符串(子

java中如何判断输入的数是不是符合为四位整数这个条件?