Integer.parseInt()函数:将字符串参数解析为带符号的十进制整数,返回由十进制参数表示的整数值。
简单点就是将String类型的数字,转换成int类型
public static void main(String[] args) {
String s="120";
int i=Integer.parseInt(s);
System.out.println(i);//输出120
}
这是parseInt函数的源码
public static int parseInt(String s, int radix)//radix默认是10
throws NumberFormatException{
if (s == null) {
throw new NumberFormatException("null");
}
//大于2
if (radix < Character.MIN_RADIX) {
throw new NumberFormatException("radix " + radix +
" less than Character.MIN_RADIX");
}
//小于36
if (radix > Character.MAX_RADIX) {
throw new NumberFormatException("radix " + radix +
" greater than Character.MAX_RADIX");
}
int result = 0;
boolean negative = false;
int i = 0, len = s.length();
int limit = -Integer.MAX_VALUE;
int multmin;
int digit;
if (len > 0) {
char firstChar = s.charAt(0);
if (firstChar < '0') { // Possible leading "+" or "-"
if (firstChar == '-') {
negative = true;
limit = Integer.MIN_VALUE;
} else if (firstChar != '+')
throw NumberFormatException.forInputString(s);
if (len == 1) // Cannot have lone "+" or "-"
throw NumberFormatException.forInputString(s);
i++;
}
multmin = limit / radix;
while (i < len) {
// Accumulating negatively avoids surprises near MAX_VALUE
digit = Character.digit(s.charAt(i++),radix);
if (digit < 0) {
throw NumberFormatException.forInputString(s);
}
if (result < multmin) {
throw NumberFormatException.forInputString(s);
}
result *= radix;
if (result < limit + digit) {
throw NumberFormatException.forInputString(s);
}
result -= digit;
}
} else {
throw NumberFormatException.forInputString(s);
}
return negative ? result : -result;
}
默认传的radix为10,就是10进制
校验传过来的数据只能为数字:
matches方法主要是返回是否匹配指定的字符串,如果匹配则为true,否则为false;
public static void main(String[] args) {
String i="72"; //输出Yes
// String i="ass"; 输出No
if(i.matches("[0-9]*")) {
System.out.println("Yes");
}else {
System.out.println("No");
}
}