1.遍历匹配
public class Test {
public static void main(String[] args) throws InterruptedException {
String s = "123456";
System.out.println(isNumber(s));
}
public static boolean isNumber(String s){
String number = "1234567890";
for (int i = 0 ; i < s.length() ; i++){
if ( number.indexOf(s.charAt(i)) == -1){ //indexOf返回()中元素的下标,没有此元素返回-1. charAt(i)返回字符串中i下标的元素
System.out.println(false);
}
}
return true;
}
}
2.ASCII码
public class Test4 {
public static void main(String[] args) throws InterruptedException {
String s = "1234567890";
System.out.println(isNumber(s));
}
public static boolean isNumber(String s){
for (int i = 0 ; i < s.length() ; i++){
if (s.charAt(i) > 47 && s.charAt(i) < 58){
return true;
}
}
return false;
}
}
3.Integer.paseInt()异常捕获。
public class Test4 {
public static void main(String[] args) throws InterruptedException {
String s = "1234567890w";
System.out.println(isNumber(s));
}
public static boolean isNumber(String s){
try{
Integer.parseInt(s);
return true;
}catch (Exception e){
return false;
}
}
}
4.正则表达式。