我正在尝试确定字符串数组中的特定项目是否为整数.
I'm trying to determine if a particular item in an Array of strings is an integer or not.
我正在 .split(" ")
'ing 一个 String
形式的中缀表达式,然后尝试将结果数组拆分为两个数组;一个用于整数,一个用于运算符,同时丢弃括号和其他杂项.实现这一目标的最佳方法是什么?
I am .split(" ")
'ing an infix expression in String
form, and then trying to split the resultant array into two arrays; one for integers, one for operators, whilst discarding parentheses, and other miscellaneous items. What would be the best way to accomplish this?
我以为我可以找到 Integer.isInteger(String arg)
方法之类的,但没有这样的运气.
I thought I might be able to find a Integer.isInteger(String arg)
method or something, but no such luck.
最简单的方法是遍历 String 并确保所有元素都是给定基数的有效数字.这是尽可能高效的方法,因为您必须至少查看每个元素一次.我想我们可以根据基数对其进行微优化,但就所有意图和目的而言,这与您所期望的一样好.
The most naive way would be to iterate over the String and make sure all the elements are valid digits for the given radix. 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;
}
或者,您可以依靠 Java 库来实现这一点.它不是基于异常的,并且会捕获您能想到的几乎所有错误情况.它会贵一点(你必须创建一个 Scanner 对象,在一个非常紧密的循环中你不想这样做.但它通常不应该太贵,所以对于日常操作应该是相当可靠的.
Alternatively, you can rely on the Java library to have this. 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.
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;
}
这篇关于确定字符串是否是Java中的整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!