出現判斷某個字符串是否能轉換能數字的需求時,應該如何處理?
一 拍腦袋方案:String轉Integer異常判斷
package test.stringutils; import org.apache.commons.lang3.StringUtils; public class StringUtilsDemo { public static void main(String[] args) { String str1 = "123"; String str2 = "hello world"; System.out.println(isNumber(str1)); System.out.println(isNumber(str2)); } public static boolean isNumber(String string) { try { Integer.parseInt(string); return true; } catch (Exception e) { return false; } } }
輸出結果:
true false
雖然能實現,但通過異常判斷進行處理,有點太暴力。
二 使用StringUtils的方法isNumeric(org.apache.commons.lang3.StringUtils)
package test.stringutils; import org.apache.commons.lang3.StringUtils; public class StringUtilsDemo { public static void main(String[] args) { String str1 = "123"; String str2 = "hello world"; System.out.println(StringUtils.isNumeric(str1)); System.out.println(StringUtils.isNumeric(str2)); } }
輸出結果:
true false
這個方案比較優雅,尤其是一些工具類,有現成的輪子就用現成的,沒必要重復造輪子。