Java代码如何检测一个字符串是否为整型呢?
下文笔者讲述一个最佳的检测字符串是否为整型的方法分享,如下所示
检测字符串是否为整型的实现思路
方式1:
对整型中的每个字符进行遍历
然后判断字符是否为数字
如果非数字,则界定为字符串无法转换为整型
方式2:
直接使用
try
catch对字符串进行转换
如果转换失败,则代表字符串为非数字
例:字符串是否为整数的示例
public static boolean isInteger(String s) {
return isInteger(s,10);
}
public static boolean isInteger(String s, int radix) {
if(s.isEmpty()) return false;
for(int i = 0; i < s.length(); i++) {
if(i == 0 && s.charAt(i) == '-') {
if(s.length() == 1) return false;
else continue;
}
if(Character.digit(s.charAt(i),radix) < 0) return false;
}
return true;
}
//或
public static boolean isInteger(String s, int radix) {
Scanner sc = new Scanner(s.trim());
if(!sc.hasNextInt(radix)) return false;
// we know it starts with a valid int, now make sure
// there's nothing left!
sc.nextInt(radix);
return !sc.hasNext();
}
//或
public static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false;
} catch(NullPointerException e) {
return false;
}
// only got here if we didn't return false
return true;
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


