Java Integer.valueOf(String)
方法
原文:https://www.studytonight.com/java-wrapper-class/java-integer-valueof-string-method
Java valueOf(String s)
方法是java.lang
包的Integer
类的一部分。此方法用于返回作为参数传递的字符串值的整数对象。
必须注意的是,该参数被视为带符号的十进制整数,该方法返回的值可以解释为new Integer(Integer.parseInt(s))
。
语法:
public static Integer valueOf(String s) throws NumberFormatException
参数:
传递的参数是要返回其等效整数对象的字符串。
例外:
NumberFormatException
: 当输入字符串不可解析时,会出现此异常。
返回:
返回作为参数传递的字符串值的整数对象。
例 1:
在这里,整数对象是根据传递的字符串值返回的。
import java.lang.Integer;
public class StudyTonight
{
public static void main(String[] args)
{
String s1 = "909";
String s2 = "253";
System.out.println("Equivalent Integer object Value = " + Integer.valueOf(s1));//returns a Integer object representing the String specified
System.out.println("Equivalent Integer object Value = " + Integer.valueOf(s2));//returns a Integer object representing the String specified
}
}
等效整数对象值= 909 等效整数对象值= 253
例 2:
这里有一个用户定义的例子,任何使用这段代码的人都可以输入自己选择的值,并获得等效的输出。
import java.lang.Integer;
import java.util.Scanner;
public class StudyTonight
{
public static void main(String[] args)
{
try
{
System.out.println("Enter the string value");
Scanner sc=new Scanner(System.in);
String x = sc.next();
System.out.println("Equivalent Integer object Value = " + Integer.valueOf(x));//returns a Integer object representing the string specified
}
catch(NumberFormatException e)
{
System.out.println("Invalid input!!");
}
}
}
输入字符串值 610 等效整数对象值= 610 *输入字符串值 0x812 无效输入!!
实时示例:
在这里,您可以测试实时代码示例。您可以为不同的值执行示例,甚至可以编辑和编写您的示例来测试 Java 代码。