java判断字符串转换为数字


一. Integer.parseInt(String str)

1. 定义字符串是否可以转换为数字的方法

/**
 * 查看一个字符串是否可以转换为数字
 * @param str 字符串
 * @return true 可以; false 不可以
 */
public static boolean isStr2Num(String str) {
    try {
        Integer.parseInt(str);
        return true;
    } catch (NumberFormatException e) {
        return false;
    }
}

2. 测试

  1. 字符串可以转换为数字
public static void test1(){
  String count = "123456";
    if(isStr2Num(count)){ //true
        int codeReActiveCount = Integer.parseInt(count);
        System.out.println(codeReActiveCount);
    }
}

输出结果:123456

  1. 字符串无法转换为数字
public static void test2(){
    String count = "123456hahaha";
    if(isStr2Num(count)){ //false
        int codeReActiveCount = Integer.parseInt(count);
        System.out.println(codeReActiveCount);
    }
}

输出结果:无输出


二. matcher.matches()

1. 定义字符串是否可以转换为数字的方法

/**
 * 定义Pattern的匹配模式常量
 */
public static String NUMBER = "^[0-9]*$";

/**
 * 查看一个字符串是否可以转换为数字
 * @param str 字符串
 * @return true 可以; false 不可以
 */
public static boolean isStr2Num(String str) {
	Pattern pattern = Pattern.compile(NUMBER);
	Matcher matcher = pattern.matcher(str);
	return matcher.matches();
}

2. 测试

String str1 = "12345";
boolean match1 = test(str1);
System.out.println(match1); // true

String str2 = "12345hahahaha";
boolean match2 = test(str2);
System.out.println(match2); // false

3. 使用

  1. 字符串可以转换为数字
public static boolean test1(){
   String str = "123456";
     if(isStr2Num(str)){  // true
		int iTemp = Integer.parseInt(str);
        System.out.println(iTemp); //123456
	}
}
  1. 字符串无法转换为数字
public static boolean test2(){
   String str = "123456xixi";
     if(isStr2Num(str)){ // false
		int iTemp = Integer.parseInt(str);
        System.out.println(iTemp); // 无输出
	}
}

三. Integer.valueOf(String s)

1. 方法描述

  1. Integer.valueOf(String s)源码
public final class Integer extends Number implements Comparable<Integer> {

	public static Integer valueOf(String s) throws NumberFormatException {
	   return Integer.valueOf(parseInt(s, 10));
	}
	
	public static int parseInt(String s) throws NumberFormatException {
	   return parseInt(s,10);
	}
}
  1. 源码说明
  • valueOf(String s) :先通过parseInt() 将字符串转换为数字,然后再转换为Integer对象。
  • parseInt(String s) :返回int 型变量。

2. 使用方法

public static void test(){
    String str = "123456xixi";
    try {
    	/**
    	 * 如果str可以转换为数字,则不会抛出异常;
    	 * 否则,抛出NumberFormatException异常
    	 */
        Integer i = Integer.valueOf(str);
        System.out.println(i);
    }catch (Exception e){
        System.out.println(e);
    }
}

参考资料

java判断字符串是否可以转为数字

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值