Java中valueOf()
方法
1.先看源代码怎么说:
Returns an Integer object holding the value of the specified String,The argument is interpreted as representing a signed decimal integer,excatly as if the argument were given to the parseInt method.The result is an Integer object that represents the integer value specified by the string.
In other words, this method returns an Integer object equal to the value of new Integer(Integer.parseInt(s))
* <blockquote>
* {@code new Integer(Integer.parseInt(s))}
* </blockquote>
*
* @param s the string to be parsed.
* @return an {@code Integer} object holding the value
* represented by the string argument.
* @exception NumberFormatException if the string cannot be parsed
* as an integer.
*/
public static Integer valueOf(String s) throws NumberFormatException {
return Integer.valueOf(parseInt(s, 10));
}
2.给出中文翻译:
返回一个由指定字符串所持有的值的整数对象,参数被翻译成一个有符号的十进制数,【这个方法的效果】就如将这个参数传递给parseInt()
方法。结果是一个由指定字符串所持有的整数对象。
换句话说,这个方法返回一个整数对象,这个整数对象和new Integer(Integer.parseInt(s))
的值相同。
- 参数:s,被接卸的字符串
- 返回值:一个由字符串【参数】代表的整数对象
- 异常:如果不能解析字符串,则抛出NumberFormatException异常
3.示例
/*
1.TestValueOf
*/
public class TestValueOf {
public static void main(String[] args) {
TestValueOf testValueOf = new TestValueOf();
testValueOf.test();
}
public void test(){
String age1 = "22";//normal decimal integer
String age2 = "fsd";
String age3 = "-2";//could recognize a signed decimal integer
String age4 = "+5";
String age5 = "24";
System.out.println(Integer.valueOf(age1));
try{
System.out.println(Integer.valueOf(age2));//can't recognize age2,because it doesn't a integer
}catch (Exception e){//to be exact,should be a NumberFormatException
System.out.println("oh,no!");
}
System.out.println(Integer.valueOf(age3));
System.out.println(Integer.valueOf(age4));
System.out.println(Integer.valueOf(age5,8));//radix is eight,but the result's radix is 10
}
}
执行结果如下:
22
oh,no!
-2
5
20
对应使用parse()
方法,同样也有:
public void test2(){
String[] str = {"22", "fsd", "-2", "+5", "24"};//使用String数组
for (int i = 0; i < str.length; i++) {
try {
System.out.println(Integer.parseInt(str[i]));
} catch (Exception e) {//to be exact,should be a NumberFormatException
System.out.println("oh,no!");
}
}
}
执行结果如下:
22
oh,no!
-2
5
24//这里是24的原因是没有传递进制