如何检查字符串是否为数字呢?
下文笔者讲述使用java代码检测字符串是否为数字的方法分享,如下所示
字符串是否为数字判断
String是否数字
实现思路:
方式1:
使用Character.isDigit()即可对单个字符进行检测判断
方式2:
使用Apache Commons Lang中的NumberUtils.isDigits进行判断
方式3:
使用try(Integer.parseInt) catch进行转换判断
例:字符串是否为数字判断
// Character.isDigit()
// 将String转换为char数组,并使用Character.isDigit()检查它
package com.java265;
public class NumericExample {
public static void main(String[] args) {
System.out.println(isNumeric("")); // false
System.out.println(isNumeric(" ")); // false
System.out.println(isNumeric(null)); // false
System.out.println(isNumeric("1,200")); // false
System.out.println(isNumeric("1")); // true
System.out.println(isNumeric("200")); // true
System.out.println(isNumeric("3000.00")); // false
}
public static boolean isNumeric(final String str) {
// null or empty
if (str == null || str.length() == 0) {
return false;
}
for (char c : str.toCharArray()) {
if (!Character.isDigit(c)) {
return false;
}
}
return true;
}
}
-----运行以上代码,将输出以下信息--------
false
false
false
false
true
true
false
//java8中使用Character.isDigit方法
public static boolean isNumeric(final String str) {
// null or empty
if (str == null || str.length() == 0) {
return false;
}
return str.chars().allMatch(Character::isDigit);
}
//使用Apache Commons Lang
//引入相关依赖
pom.xml
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
import org.apache.commons.lang3.math.NumberUtils;
public static boolean isNumeric(final String str) {
return NumberUtils.isDigits(str);
}
//使用NumberFormatException(try catch进行验证判断)
public static boolean isNumeric(final String str) {
if (str == null || str.length() == 0) {
return false;
}
try {
Integer.parseInt(str);
return true;
} catch (NumberFormatException e) {
return false;
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


