問題描述
我正在嘗試確定字符串數組中的特定項目是否為整數.
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中的整數的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!