Java Integer.valueOf(String,int)方法

原文:https://www.studytonight.com/java-wrapper-class/java-integer-valueof-string-int-method

Java valueOf(String s,int radix)方法是java.lang包的Integer类的一部分。当使用作为参数传递的整数基数值分析字符串值时,此方法用于返回作为参数传递的字符串值的整数对象的值。

需要注意的是,这个方法返回的值可以解释为new Integer(Integer.parseInt(s,radix))

语法:

public static Integer valueOf(String s, int radix) throws NumberFormatException

参数:

传递的参数是将返回其整数对象的等值的字符串,以及将根据其解析输入字符串的整数基数值。

例外:

NumberFormatException : 当输入字符串不可解析时,会出现此异常。

返回:

根据基数值,返回作为参数传递的字符串值的整数对象的值。

例 1:

这里,根据传递的整数基数,返回字符串值的整数对象表示。

import java.lang.Integer;

public class StudyTonight
{  
        public static void main(String[] args)throws NumberFormatException 
        { 
            String s = "603";  
            int radix = 16;  
            System.out.print("\nEntered value and Base value is: " + s + " and " + radix);  
           //returns the Integer object of the entered string in accordance with the radix            
            System.out.println("\nEquivalent Integer object is " + Integer.valueOf(s, radix)); 
        }  
}

输入值和基础值为:603 和 16 等效整数对象为 1539

例 2:

这里有一个用户定义的例子,任何使用这段代码的人都可以输入自己选择的值,并获得等效的输出。

import java.util.Scanner; 
public class StudyTonight
{  
    public static void main(String[] args)
    {  
        try
        {
          System.out.print("Enter the value: ");  
          Scanner sc = new Scanner(System.in);  
          String s = sc.nextLine();  
          System.out.print("Enter the radix: "); 
          int radix = sc.nextInt();
          System.out.println("Equivalent Integer object : " +Integer.valueOf(s,radix)); //returns the Integer object value of the string with respect to radix 
        }
        catch(NumberFormatException e)
        {
          System.out.println("Invalid Input!!");
        }         
    }  
}

输入数值:631 输入基数:8 等效整数对象:409

                                                      • T4】输入数值:0x678 输入基数:16 无效输入!!

实时代码:

在这里,您可以测试实时代码示例。您可以为不同的值执行示例,甚至可以编辑和编写您的示例来测试 Java 代码。