URL original: Serie de cadenas de Java: juzgar si una cadena es un número
Introducción
Este artículo presenta el método de Java para determinar si una cadena es un número.
Método 1: juicio de un solo carácter
public static boolean checkIsNumeric(String str) {
String tmpStr = str;
// 判断负数
if (str.startsWith("-")) {
tmpStr = str.substring(1);
}
for (int i = tmpStr.length(); --i >= 0; ) {
if (!Character.isDigit(tmpStr.charAt(i))) {
return false;
}
}
return true;
}
Método 2: expresiones regulares
// import java.util.regex.Pattern;
public static boolean checkIsNumeric(String str) {
Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
return pattern.matcher(str).matches();
}
Método 3: método de análisis de números enteros
public static boolean checkIsNumeric(String str) {
try {
Integer.parseInt(str);
} catch (NumberFormatException e) {
return false;
}
return true;
}
Método 4: código Ascii
public static boolean checkIsNumeric(String str) {
String tmpStr = str;
// 判断负数
if (str.startsWith("-")) {
tmpStr = str.substring(1);
}
for (int i = tmpStr.length(); --i >= 0; ) {
int chr = tmpStr.charAt(i);
if (chr < 48 || chr > 57)
return false;
}
return true;
}