Java中valueOf()方法
2023-09-14 09:13:18 时间
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的原因是没有传递进制
相关文章
- Java中Date类中getTime()方法
- java实现亲密数
- Java实现 蓝桥杯 历届试题 邮局
- Java中Vector类的常用方法
- Java中BigDecimal类的常用方法
- Java实现蓝桥杯历届试题高僧斗法
- Java 三种方式实现接口校验
- atitit.判断时间重叠方法总结 java c++ c#.net js php
- atitit.判断时间重叠方法总结 java c++ c#.net js php
- atitit.java给属性赋值方法总结and BeanUtils 1.6.1 .copyProperty的bug
- paip.java c++得到当前类,方法名称以及行号
- java中的方法定义以及访问修饰符
- 成功解决 raise RuntimeError(“The JPMML-SkLearn conversion application has failed. The Java executable
- Java中的抽象类和抽象方法是什么?概述到解析层层深入了解
- Java之Serializable接口实现序列化和反序列化实例以及部分序列化的四种方法
- Java-小技巧-005-double类型保留两位小数4种方法
- 使用java模拟简单的tomcat