java中判断字符串是否是整数的方法-创新互联

这篇文章将为大家详细讲解有关java中判断字符串是否是整数的方法,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

海珠ssl适用于网站、小程序/APP、API接口等需要进行数据传输应用场景,ssl证书未来市场广阔!成为成都创新互联的ssl证书销售渠道,可以享受市场价格4-6折优惠!如果有意向欢迎电话联系或者加微信:028-86922220(备注:SSL证书合作)期待与您的合作!

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");
下面的解释:
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]+”即可匹配所有数字。

关于java中判断字符串是否是整数的方法就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。


分享文章:java中判断字符串是否是整数的方法-创新互联
链接URL:http://bzwzjz.com/article/ccpssp.html

其他资讯

Copyright © 2007-2020 广东宝晨空调科技有限公司 All Rights Reserved 粤ICP备2022107769号
友情链接: 网站制作公司 重庆网站建设 成都定制网站建设 成都网站建设 移动手机网站制作 梓潼网站设计 成都网站制作 四川成都网站制作 品牌网站建设 成都网站建设 手机网站制作设计 上市集团网站建设 成都网站建设 做网站设计 成都网站设计 成都网站建设 成都模版网站建设 成都网站设计 app网站建设 网站制作 成都网站设计 成都网站建设推广