1、用java自带的函数
public static boolean isnumeric(string str){ for (int i = str.length();--i>=0;){ if (!character.isdigit(str.charat(i))){ return false; } } return true; }
2、用正则表达式
public static boolean isnumeric(string str){ pattern pattern = pattern.compile("[0-9]*"); return pattern.matcher(str).matches(); }
3、用ascii码
public static boolean isnumeric(string str){ for(int i=str.length();--i>=0;){ int chr=str.charat(i); if(chr<48 || chr>57) return false; } return true; }
4、捕获numberformatexception异常
public static boolean isnumeric00(string str){ try{ integer.parseint(str); return true; }catch(numberformatexception e) { system.out.println("异常:\"" + str + "\"不是数字/整数..."); return false; }}
更多java知识请关注java基础教程。
以上就是java判断是否为一个数字的详细内容。
