java判断string变量是否是数字的六种方法小结

(2012-10-17 17:00:17)

标签:

it

分类: 转发
1.用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;
}
 
2.用正则表达式
首先要import java.util.regex.Pattern 和 java.util.regex.Matcher
public boolean isNumeric(String str){
   Pattern pattern = Pattern.compile("[0-9]*");
   Matcher isNum = pattern.matcher(str);
   if( !isNum.matches() ){
       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下面的解释:
isNumeric
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)   = false
StringUtils.isNumeric("")     = true
StringUtils.isNumeric(" ")   = false
StringUtils.isNumeric("123") = true
StringUtils.isNumeric("12 3") = false
StringUtils.isNumeric("ab2c") = false
StringUtils.isNumeric("12-3") = false
StringUtils.isNumeric("12.3") = false
 
Parameters:
str - the String to check, may be null
Returns:
true if only contains digits, and is non-null
 
上面三种方式中,第二种方式比较灵活。
 
第一、三种方式只能校验不含负号“-”的数字,即输入一个负数-199,输出结果将是false;
 
而第二方式则可以通过修改正则表达式实现校验负数,将正则表达式修改为“^-?[0-9]+”即可,修改为“-?[0-9]+.?[0-9]+”即可匹配所有数字。
 
如果我输入的是"a“,它能识别出来这个不是数字,该怎么写?
 
import java.io.* ;
import java.util.* ;
public class Test{
public static void main(String [] args) throws Exception{
System.out.println("请输入数字:");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
   String line=br.readLine();
 
    if(line.matches("\\d+"))     //正则表达式 详细见java.util.regex 类 Pattern
   System.out.println("数字");
   else
   System.out.println("非数字");
}
}
 
("\d")是数字0-9 ("\\d+")是什么意思?
正则表达式用两个斜杠表示一个斜杠,后面跟着一个加号表示出现一次或多次,完整的意思就是整个字符串中仅包含一个或多个数字。
 
 
    //4、判断ASCII码值
 public static boolean isNumeric0(String str){
  for(int i=str.length();--i>=0;){
   int chr=str.charAt(i);
   if(chr<48 || chr>57)
    return false;
  }
  return true;
 }
    //5、逐个判断str中的字符是否是0-9
 public static boolean isNumeric3(String str){
  final String number = "0123456789";
  for(int i = 0;i
            if(number.indexOf(str.charAt(i)) == -1){  
             return false;  
            }  
  }  
  return true;
 }
    //6、捕获NumberFormatException异常
 public static boolean isNumeric00(String str){
  try{
   Integer.parseInt(str);
   return true;
  }catch(NumberFormatException e){
   System.out.println("异常:\"" + str + "\"不是数字/整数...");
   return false;
  }
 }
 
 ps:不提倡使用方法6,原因如下:
    1、NumberFormatException是用来处理异常的,最好不要用来控制流程的。  
    2、虽然捕捉一次异常很容易,但是创建一次异常会消耗很多的系统资源,因为它要给整个结构作一个快照。 
 看一下JDK源码:
 public static long parseLong(String s,int radix)  
         throws NumberFormatException  
 {  
    if(s == null){  
       throw   new   NumberFormatException("null");  
    }  
    if(radix < Character.MIN_RADIX){  
           throw new NumberFormatException("radix " + radix +
           " less than Character.MIN_RADIX");  
    }  
    if(radix > Character.MAX_RADIX){  
           throw new NumberFormatException("radix " + radix +
           " greater than Character.MAX_RADIX");  
    }  
    long result = 0;  
    boolean negative = false;
    int i = 0,max = s.length();  
    long limit;  
    long multmin;  
    int digit;
    if(max > 0){  
     if(s.charAt(0) == '-'){  
      negative = true;  
      limit = Long.MIN_VALUE;
      i++;
     }else{
      limit = -Long.MAX_VALUE;
     }  
     multmin = limit / radix;
     if(i < max){  
      digit = Character.digit(s.charAt(i++),radix);  
      if(digit < 0){
            throw new NumberFormatException(s);  
      }else{  
            result = -digit;
      }  
     }  
     while(i < max){  
      // Accumulating negatively avoids surprises near MAX_VALUE
      digit = Character.digit(s.charAt(i++),radix);  
      if(digit < 0){  
       throw new NumberFormatException(s);  
      }  
      if(result < multmin){  
       throw new NumberFormatException(s);  
      }  
      result *= radix;  
      if(result < limit + digit){  
       throw new NumberFormatException(s);  
      }  
      result -= digit;  
    }  
    }else{  
     throw   new   NumberFormatException(s);  
    }  
    if(negative){  
     if(i > 1){  
      return result;
     }else{  
      throw new NumberFormatException(s);  
     }  
    }else{  
     return   -result;  
    }  
 }  
 可以看出来jdk里也是一个字符一个字符的判断,如果有一个不是数字就抛出NumberFormatException,所以还不如这个工作由我们自己来做,还省得再抛出一次异常... 
 
 
用4比较方便

(转)java判断string变量是否是数字的六种方法小结的更多相关文章

  1. Java判断一个字符是否是数字的几种方法的代码

    在工作期间,将写内容过程经常用到的一些内容段做个记录,下面内容是关于Java判断一个字符是否是数字的几种方法的内容,希望能对码农们有好处. public class Test{ public stat ...

  2. java 判断String字符串是不是json数据

      java 判断String字符串是不是json数据 CreationTime--2018年8月24日18点23分 Author:Marydon JSONObject jo = null; try ...

  3. Java 判断字符串是否为空的四种方法、优缺点与注意事项

    以下是Java 判断字符串是否为空的四种方法: 方法一: 最多人使用的一个方法, 直观, 方便, 但效率很低: if(s == null ||"".equals(s));方法二: ...

  4. java 判断一个字符串中的数字:是否为数字、是否包含数字、截取数字

    题外话: JavaScript中判断一个字符是否为数字,用函数:isDigit(); 一.判断一个字符串是否都为数字 package com.cmc.util; import java.util.re ...

  5. Java判断一个字符串str不为空:方法及时间效率

    判断一个字符串str不为空的方法有: 1.str == null; 2.”“.equals(str): 3.str.length <= 0; 4.str.isEmpty(): 注意:length ...

  6. 判断String类型字符串是否为空的方法

    在项目中经常遇到要判断String类型的字段是否为空操作 我们可以用Apache提供的StringUtils这个工具类,不用自己去判断,也不用自己封装判断空的方法 它有两个版本,一个是org.apac ...

  7. python3 之 判断字符串是否只为数字(isdigit()方法、isnumeric()方法)

    Isdigit()方法 - 检测字符串是否只由数字组成 语法:   str.isdigit() 参数: 无 返回值: 如果字符串只包含数字,则返回True,否则返回False. 实例: 以下实例展示了 ...

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

    正则表达式 首先要import java.util.regex.Pattern 和 java.util.regex.Matcher public boolean isNumeric(String st ...

  9. java判断一个字符串是否为数字型

    摘自:https://blog.csdn.net/qq_42133100/article/details/92158507 方法一:用JAVA自带的函数(只能判断正整数 ) 2 public stat ...

随机推荐

  1. hdu-5794 A Simple Chess(容斥+lucas+dp)

    题目链接: A Simple Chess Time Limit: 2000/1000 MS (Java/Others)     Memory Limit: 65536/65536 K (Java/Ot ...

  2. java线程数据交换Exchanger

    两个线程都等到交换函数才能完成交换数据操作,代码如下: package threadLock; import java.util.Random; import java.util.concurrent ...

  3. android log 学习

    一,Bug出现了, 需要“干掉”它 bug一听挺吓人的,但是只要你懂了,android里的bug是很好解决的,因为android里提供了LOG机制,具体的底层代码,以后在来分析,只要你会看bug, a ...

  4. C++primer 9.49

    题目:如果一个字母延伸到中线之上,如d或f,则称其有上出头部分(ascender).如果一个字母延伸到中线之下,如p或g,则称其有下出头部分(descender).编写程序,读入一个单词文件,输出最长 ...

  5. %02d

    %d表示打印整型的,%2d表示把整型数据打印最低两位,%02d表示把整型数据打印最低两位,如果不足两位,用0补齐所以打印出来就是02了

  6. svn rollback: 恢复到上一版本

    18:48:32svn的文件版本是168,我想用167的版本覆盖掉168的版本如何搞? 18:52:47先把本地的那个文件用rm命令删掉,然后,使用svn up -r 167 文件路径,UP下来的文件 ...

  7. Linux启动流程详解【转载】

    在BIOS阶段,计算机的行为基本上被写死了,可以做的事情并不多:一般就是通电.BIOS.主引导记录.操作系统这四步.所以我们一般认为加载内核是linux启动流程的第一步. 第一步.加载内核 操作系统接 ...

  8. 【实验室笔记】太阳能板清洁器DEMO

    <太阳能板清洁器DEMO>2015年的毕昇杯比赛作品,用时两天,整体设计思路很简单: [机械结构]: 清洁器主体采用角钢搭建,用钢锯切割好以后,上螺丝,走线用的尼龙扎带捆绑: 清洗滚轮采用 ...

  9. linux配置使用外部smtp发送邮件

    mail命令需要设定mail.rc(或nail.rc)文件, set from=user@domain.comset smtp=smtp.domain.comset smtp-auth-user=us ...

  10. headless

    http://www.oschina.net/translate/using-headless-mode-in-java-se