java怎么判斷變量是否為數字?針對這個問題,這篇文章給出了相對應的分析和解答,希望能幫助更多想解決這個問題的朋友找到更加簡單易行的辦法。
1、用JAVA自帶的函數
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");
http://jakarta.apache.org/commons/lang/api-release/index.html下面的解釋:
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") = falseParameters: str - the String to check, may be null Returns: true if only contains digits, and is non-null
上面三種方式中,第二種方式比較靈活。
第一、三種方式只能校驗不含負號“-”的數字,即輸入一個負數-199,輸出結果將是false;
而第二方式則可以通過修改正則表達式實現校驗負數,將正則表達式修改為“^-?[0-9]+”即可,修改為“-?[0-9]+.?[0-9]+”即可匹配所有數字。
如果我輸入的是"a“,它能識別出來這個不是數字,該怎么寫?
import java.io.* ;
import java.util.* ;
public class Test{
public static void main(String [] args) throws Exception{
System.out.println("請輸入數字:");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String line=br.readLine();
if(line.matches("\\d+")) //正則表達式 詳細見java.util.regex 類 Pattern
System.out.println("數字");
else
System.out.println("非數字");
}
}("\d")是數字0-9 ("\\d+")是什么意思?
正則表達式用兩個斜杠表示一個斜杠,后面跟著一個加號表示出現一次或多次,完整的意思就是整個字符串中僅包含一個或多個數字。
4、判斷ASCII碼值
public static boolean isNumeric0(String str){
for(int i=str.length();--i>=0;){
int chr=str.charAt(i);
if(chr<48 || chr>57)
return false;
}
return true;
}5、逐個判斷str中的字符是否是0-9
public static boolean isNumeric3(String str){
final String number = "0123456789";
for(int i = 0;i
if(number.indexOf(str.charAt(i)) == -1){
return false;
}
}
return true;
}6、捕獲NumberFormatException異常
public static boolean isNumeric00(String str){
try{
Integer.parseInt(str);
return true;
}catch(NumberFormatException e){
System.out.println("異常:\"" + str + "\"不是數字/整數...");
return false;
}
}ps:不提倡使用方法6,原因如下:
1、NumberFormatException是用來處理異常的,最好不要用來控制流程的。
2、雖然捕捉一次異常很容易,但是創建一次異常會消耗很多的系統資源,因為它要給整個結構作一個快照。
看一下JDK源碼:
public static long parseLong(String s,int radix)
throws NumberFormatException
{
if(s == null){
throw new NumberFormatException("null");
}
if(radix < Character.MIN_RADIX){
throw new NumberFormatException("radix " + radix +
" less than Character.MIN_RADIX");
}
if(radix > Character.MAX_RADIX){
throw new NumberFormatException("radix " + radix +
" greater than Character.MAX_RADIX");
}
long result = 0;
boolean negative = false;
int i = 0,max = s.length();
long limit;
long multmin;
int digit;
if(max > 0){
if(s.charAt(0) == '-'){
negative = true;
limit = Long.MIN_VALUE;
i++;
}else{
limit = -Long.MAX_VALUE;
}
multmin = limit / radix;
if(i < max){
digit = Character.digit(s.charAt(i++),radix);
if(digit < 0){
throw new NumberFormatException(s);
}else{
result = -digit;
}
}
while(i < max){
// Accumulating negatively avoids surprises near MAX_VALUE
digit = Character.digit(s.charAt(i++),radix);
if(digit < 0){
throw new NumberFormatException(s);
}
if(result < multmin){
throw new NumberFormatException(s);
}
result *= radix;
if(result < limit + digit){
throw new NumberFormatException(s);
}
result -= digit;
}
}else{
throw new NumberFormatException(s);
}
if(negative){
if(i > 1){
return result;
}else{
throw new NumberFormatException(s);
}
}else{
return -result;
}
}可以看出來jdk里也是一個字符一個字符的判斷,如果有一個不是數字就拋出NumberFormatException,所以還不如這個工作由我們自己來做,還省得再拋出一次異常。
關于java判斷變量是否為數字的方法就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。