1.用JAVA自带的函数
package com.luna.test;
public class IsNUmber {
public static void main(String[] args) {
String s1 = "10";
String s2 = "-10";
String s3 = "a10";
String s4 = "10b";
String s5 = "01";
System.out.println(isNumerOrigin(s1));
System.out.println(isNumerOrigin(s2));
System.out.println(isNumerOrigin(s3));
System.out.println(isNumerOrigin(s4));
System.out.println(isNumerOrigin(s5));
}
public static boolean isNumerOrigin(String str) {
for (int i = 0; i < str.length(); i++) {
if (!Character.isDigit(str.charAt(i))) {
return false;
}
}
return true;
}
}
输出结果:true,false,false,false,true。注意:这种方式不能用来判断负数。
2.用正则表达式
package com.luna.test;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class IsNUmber {
public static void main(String[] args) {
String s1 = "10";
String s2 = "-10";
String s3 = "a10";
String s4 = "10b";
String s5 = "01";
System.out.println(isNumerRule(s1));
System.out.println(isNumerRule(s2));
System.out.println(isNumerRule(s3));
System.out.println(isNumerRule(s4));
System.out.println(isNumerRule(s5));
}
public static boolean isNumerRule(String str) {
Pattern pattern = Pattern.compile("-?[0-9]+\\.?[0-9]*");
Matcher isNum = pattern.matcher(str);
if (!isNum.matches()) {
return false;
}
return true;
}
}
输出结果:true,true,false,false,true。适用于任何正负数字。
3.判断是否为整数(非严格数字判断)
/**
* 判斷是否為整數
* @param str
* @return
*/
public static boolean isNumer(String str) {
Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
return pattern.matcher(str).matches();
}
/**
* 判斷是否為正整數
* @param str
* @return
*/
public static boolean isNumerInteger(String str) {
if (str != null && !"".equals(str.trim())) {
return str.matches("^[0-9]*$");
}
return false;
}
/**
* 判斷是否為正整數
* @param str
* @return
*/
public static boolean isNumericInt (String str) {
Pattern pattern = Pattern.compile("[0-9]*");
return pattern.matcher(str).matches();
}