本文目錄一覽:
java 編程 判斷字符串是否為【數值字符串】
我知道的方法中,兩種已經被你禁用了。只剩下逐個字符判斷的方法了。Character類有判斷字符是否為數字的方法isDigit
public static boolean isNumeric(String token) {
for (int i = 0; i token.length(); i++) {
if (!Character.isDigit(token.charAt(i))) {
return false;//有一個字符不是數字則整個token不是數字,返回false
}
}
//都是數字返回true;
return true;
}
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”);
下面的解釋:
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
上面三種方式中,第二種方式比較靈活。
第一、三種方式只能校驗不含負號「-」的數字,即輸入一個負數-199,輸出結果將是false;
而第二方式則可以通過修改正則表達式實現校驗負數,將正則表達式修改為「^-?[0-9]+」即可,修改為「-?[0-9]+.?[0-9]+」即可匹配所有數字。
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(“該字符串不是純數字”);}}}方法
java中驗證字符串是不是數字的四種方法
判斷字符串是不是數字,大家可能會用一些java自帶的方法,也有可能用其他怪異的招式,比如判斷是不是整型數字,將字符串強制轉換成整型,不是數字的就會拋出錯誤,那麼就不是整型的了。但本文介紹的比較好的兩種方法:
1。java類庫自帶的方法:
public boolean isNum(String msg){
if(java.lang.Character.isDigit(msg.charAt(0))){
return true;}return false;}0202更新:發現以上方法寫得不夠到位,現在就改為下面的簡單說明了,至於具體的方法實現字符串判斷是否數字就不寫了。
java.lang.Character.isDigit(char ch) boolean
isDigit 只能作用於char,所以判斷字符串是否為數字,要一個一個拿出char進行判斷。
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;}02
3。用正則表達式
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/302747.html