代码:
package test; import java.util.regex.Pattern; /** * 判断字符串是否整数的三种方式,孰优孰劣请自行判断 * */ public class Test6 { public static void main(String[] args) { String[] arr= {"123","007","0000","1A","哈哈","Tank","100000000","00000001","100Z996","100996l",}; for(String s:arr) { boolean result1=isInteger1(s); System.out.println("isInteger1认为:"+s+(result1?"是":"不是")+"整数"); boolean result2=isInteger2(s); System.out.println("isInteger2认为:"+s+(result2?"是":"不是")+"整数"); boolean result3=isInteger3(s); System.out.println("isInteger3认为:"+s+(result3?"是":"不是")+"整数"); System.out.println(); } } public static boolean isInteger1(String s) { try { Integer.parseInt(s); return true; }catch(Exception ex) { return false; } } public static boolean isInteger2(String s) { char[] arr=s.toCharArray(); for(char c:arr) { if(Character.isDigit(c)==false) { return false; } } return true; } public static boolean isInteger3(String s) { Pattern pattern = Pattern.compile("[1-9]+[0-9]*"); return pattern.matcher(s).matches(); } }
输出:
isInteger1认为:123是整数
isInteger2认为:123是整数
isInteger3认为:123是整数
isInteger1认为:007是整数
isInteger2认为:007是整数
isInteger3认为:007不是整数
isInteger1认为:0000是整数
isInteger2认为:0000是整数
isInteger3认为:0000不是整数
isInteger1认为:1A不是整数
isInteger2认为:1A不是整数
isInteger3认为:1A不是整数
isInteger1认为:哈哈不是整数
isInteger2认为:哈哈不是整数
isInteger3认为:哈哈不是整数
isInteger1认为:Tank不是整数
isInteger2认为:Tank不是整数
isInteger3认为:Tank不是整数
isInteger1认为:100000000是整数
isInteger2认为:100000000是整数
isInteger3认为:100000000是整数
isInteger1认为:00000001是整数
isInteger2认为:00000001是整数
isInteger3认为:00000001不是整数
isInteger1认为:100Z996不是整数
isInteger2认为:100Z996不是整数
isInteger3认为:100Z996不是整数
isInteger1认为:100996l不是整数
isInteger2认为:100996l不是整数
isInteger3认为:100996l不是整数
END