The most naive way would be to iterate over the String and make sure all the elements are valid digits for the given radix.
(最幼稚的方法是遍历String并确保所有元素都是给定基数的有效数字。)
This is about as efficient as it could possibly get, since you must look at each element at least once. (由于您必须至少查看一次每个元素,因此这将尽可能地提高效率。)
I suppose we could micro-optimize it based on the radix, but for all intents and purposes this is as good as you can expect to get. (我想我们可以根据基数对其进行微优化,但是就所有意图和目的而言,这都是您所期望的那样好。)
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;
}
Alternatively, you can rely on the Java library to have this.
(另外,您可以依靠Java库来实现。)
It's not exception based, and will catch just about every error condition you can think of. (它不是基于异常的,并且将捕获几乎所有您能想到的错误条件。)
It will be a little more expensive (you have to create a Scanner object, which in a critically-tight loop you don't want to do. But it generally shouldn't be too much more expensive, so for day-to-day operations it should be pretty reliable. (它会贵一点(您必须创建一个Scanner对象,该对象在严格的紧缩循环中是您不希望做的。但是通常它不会太贵,所以对于每天操作它应该是相当可靠的。)
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();
}
If best practices don't matter to you, or you want to troll the guy who does your code reviews, try this on for size:
(如果最佳实践对您来说并不重要,或者您想招揽进行代码审查的人员,请尝试以下方法以获取大小:)
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;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…