URL d'origine : Série de chaînes de Java – Juger si une chaîne est un nombre
Introduction
Cet article présente la méthode Java pour déterminer si une chaîne est un nombre.
Méthode 1 : jugement d’un seul personnage
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éthode 2 : expressions régulières
// import java.util.regex.Pattern;
public static boolean checkIsNumeric(String str) {
Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
return pattern.matcher(str).matches();
}
Méthode 3 : méthode d’analyse des entiers
public static boolean checkIsNumeric(String str) {
try {
Integer.parseInt(str);
} catch (NumberFormatException e) {
return false;
}
return true;
}
Méthode 4 : code 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;
}