1、使用java自带的函数
public static boolean isNumeric1(String str){ int len=str.length(); if(len>1&&str.charAt(0)=='0'){//当大于2位时,左起第一位不能为0 return false; } for(int i=0;i<len;i++){//左起每一位都不能为除数字外其他字符 char iStr=str.charAt(i); if(!Character.isDigit(iStr)){ return false; } } return true; }
2、采用正则表达式
public static boolean isNumeric1(String str){ Pattern pattern=Pattern.compile("^-?([0-9])|([1-9][0-9]{1,})$"); return pattern.matcher(str).matches(); }