這篇文章將為大家詳細講解有關java中判斷字符串是否是整數(shù)的方法,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
1、用JAVA自帶的函數(shù)
public static boolean isNumeric(String str){ for (int i = 0; i < str.length(); i++){ System.out.println(str.charAt(i)); if (!Character.isDigit(str.charAt(i))){ return false; } } return true; }
2、用正則表達式
首先要import java.util.regex.Pattern 和 java.util.regex.Matcher
public boolean isNumeric(String str){ Pattern pattern = Pattern.compile("[0-9]*"); Matcher isNum = pattern.matcher(str); if( !isNum.matches() ){ return false; } return true; }
3、使用org.apache.commons.lang
org.apache.commons.lang.StringUtils; boolean isNunicodeDigits=StringUtils.isNumeric("aaa123456789"); 下面的解釋: isNumeric public static boolean isNumeric(String str)Checks if the String contains only unicode digits. A decimal point is not a unicode digit and returns false. null will return false. An empty String ("") will return true. StringUtils.isNumeric(null) = false StringUtils.isNumeric("") = true StringUtils.isNumeric(" ") = false StringUtils.isNumeric("123") = true StringUtils.isNumeric("12 3") = false StringUtils.isNumeric("ab2c") = false StringUtils.isNumeric("12-3") = false StringUtils.isNumeric("12.3") = false Parameters: str - the String to check, may be null Returns: true if only contains digits, and is non-null
上面三種方式中,第二種方式比較靈活。
第一、三種方式只能校驗不含負號“-”的數(shù)字,即輸入一個負數(shù)-199,輸出結果將是false;
而第二方式則可以通過修改正則表達式實現(xiàn)校驗負數(shù),將正則表達式修改為“^-?[0-9]+”即可,修改為“-?[0-9]+.?[0-9]+”即可匹配所有數(shù)字。
關于java中判斷字符串是否是整數(shù)的方法就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
網(wǎng)站標題:java中判斷字符串是否是整數(shù)的方法-創(chuàng)新互聯(lián)
URL分享:http://aaarwkj.com/article38/ccpssp.html
成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供定制開發(fā)、云服務器、網(wǎng)站內(nèi)鏈、小程序開發(fā)、網(wǎng)站改版、品牌網(wǎng)站設計
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉載內(nèi)容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容