java中判断字符串是否是整数的方法

发布时间:2020-06-25 12:08:43 作者:Leah
来源:亿速云 阅读:406

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

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

推荐阅读:
  1. java怎么判断字符串是否是整数
  2. java中怎么判断字符串是否为整数

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java ava

上一篇:Scala下Play框架学习笔记(Http Routing)

下一篇:使用windows部署服务安装操作系统时错误

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》