java 关于字符串是否为数字的判断
对于给定的字符串,要对其是否为数字的判断,一般常用的方法有:
1.使用基本类型的封装类的转化方法,进行判断,如果有异常抛出,则不为数字,否则为数字。由于无法确定数字位数,该方法不建议使用,防止超过该类型的最大上限。
例如:
public static void main(String[] args) { String str = "1234"; try { double d1 = Double.parseDouble(str); //float f1 = Float.parseFloat(str); //int i1 = Integer.parseInt(str); System.out.println("该字符串是数字!"); } catch (Exception e) { System.out.println("该字符串不是数字!"); } }
2.将字符串转化为字符数组,遍历字符数组,判断是否为数字
例如:
public static void main(String[] args) { String str = "1234"; char[] chs = str.toCharArray(); for (int i = 0; i < chs.length; i++) { if(!Character.isDigit(chs[i])){ System.out.println("该字符串不是数字!"); System.exit(0); } } System.out.println("该字符串是数字!"); }
3.将字符串转化为字符数组,遍历字符数组,利用ASASCII码进行判断
例如:
public static void main(String[] args) { String str = "1234"; char[] chs = str.toCharArray(); for (int i = 0; i < chs.length; i++) { if(chs[i]<48||chs[i]>57){ System.out.println("该字符串不是数字!"); System.exit(0); } } System.out.println("该字符串是数字!"); }
4.使用正则表达式进行判断
例如:
public static void main(String[] args) { String str = "1234"; String reg = "^[0-9]*$"; if(str.matches(reg)){ System.out.println("该字符串是数字!"); }else{ System.out.println("该字符串不是数字!"); } }