文章目录
一. 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. 测试
- 字符串可以转换为数字
public static void test1(){
String count = "123456";
if(isStr2Num(count)){ //true
int codeReActiveCount = Integer.parseInt(count);
System.out.println(codeReActiveCount);
}
}
输出结果:123456
- 字符串无法转换为数字
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. 使用
- 字符串可以转换为数字
public static boolean test1(){
String str = "123456";
if(isStr2Num(str)){ // true
int iTemp = Integer.parseInt(str);
System.out.println(iTemp); //123456
}
}
- 字符串无法转换为数字
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. 方法描述
- 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);
}
}
- 源码说明
- 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);
}
}