本文目錄一覽:
java中判斷字符串是否為純數字
方法一:利用正則表達式public class Testone {public static void main(String[] args){String str=”123456″;boolean result=str.matches(“[0-9]+”);if (result == true) {System.out.println(“該字符串是純數字”);}else{System.out.println(“該字符串不是純數字”);}}}方法二:利用Pattern.import java.util.regex.Matcher;import java.util.regex.Pattern;public class Testone {public static void main(String[] args){String str=”123456″;Pattern pattern = Pattern.compile(“[0-9]{1,}”);Matcher matcher = pattern.matcher((CharSequence)str);boolean result=matcher.matches();System.out.println(“該字符串是純數字”);}else{System.out.println(“該字符串不是純數字”);}}}
Java 中怎樣判斷一個字符串全是數字
Java中判斷字符串是否全是數字:
可以使用正則表達式:
public boolean isNumeric(String str) {
Pattern pattern = Pattern.compile(“[0-9]*”);
Matcher isNum = pattern.matcher(str);
if (!isNum.matches()) {
return false;
}
return true;
}
但是這個方法並不安全,沒有對字符串進行空校驗。
在程序執行的時候很容易拋出異常。
例如執行:
public static void main(String[] args) {
String str = null;
System.out.println(BarcodeChecksum.INSTANCE.isNumeric(str));
}
就會拋出異常:
Exception in thread “main” java.lang.NullPointerException
at java.util.regex.Matcher.getTextLength(Matcher.java:1140)
at java.util.regex.Matcher.reset(Matcher.java:291)
at java.util.regex.Matcher.init(Matcher.java:211)
at java.util.regex.Pattern.matcher(Pattern.java:888)
at com.ossez.bcu.util.BarcodeChecksum.isNumeric(BarcodeChecksum.java:37)
at com.ossez.bcu.util.BarcodeChecksum.main(BarcodeChecksum.java:53)
所以這個方法並不準確。
如果執行:
public static void main(String[] args) {
String str = “”;
System.out.println(BarcodeChecksum.INSTANCE.isNumeric(str));
}
將會返回 true。
這說明這個方法沒有對空字符串進行校驗。
可以使用 Apache 的 StringUtils.isNumeric() 函數進行判斷。
這個函數位於 org.apache.commons.lang.StringUtils; 中。
但是,需要注意,如果傳入參數為 “” 同樣也會你存在判斷不準確的情況,這時候需要首先對需要進行判斷的參數進行非空校驗,然後刪除傳入數據中的空格。
public static void main(String[] args) {
String str = “”;
System.out.println(StringUtils.isNumeric(str));
}
上面這個函數將會返回 true。
請先 trim 數據
java 里怎麼判斷一個字符串是不是純數字
public class AllNumber {
/**
* 使用Double.parseDouble方法判斷字符串是不是為數字
*
* @param number
* 字符串
* @return
*/
public static boolean isNumber(String number) {
if (null == number) {
return false;
}
try {
double num = Double.parseDouble(number);// 轉換成功則是數字
} catch (Exception e) {
// TODO: handle exception
return false;
}
return true;
}
/**
* 使用正則表達式判斷字符串是不是為數字
*
* @param number
* 字符串
* @return
*/
public static boolean isNumberByRegex(String number) {
if (null == number) {
return false;
}
String regex = “^[-]{0,1}[0-9]{1,}[.]{0,1}[0-9]{1,}$”;
return number.matches(regex);
}
public static void main(String[] args) {
System.out.println(isNumber(“1234.90”));
System.out.println(isNumberByRegex(“-0123.9”));
}
}
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/296225.html