Java - Integer valueOf(String s, int radix) 方法



描述

Java Integer valueOf(String s, int radix) 方法返回一个 Integer 对象,该对象包含从指定字符串 s 中提取的值,该值在使用第二个参数 radix 给出的基数进行解析时提取。

声明

以下是 java.lang.Integer.valueOf() 方法的声明

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

参数

  • s − 要解析的字符串。

  • radix − 用于解释 s 的基数。

返回值

此方法返回一个 Integer 对象,该对象保存字符串参数以指定基数表示的值。

异常

NumberFormatException − 如果字符串不包含可解析的 int。

使用基数 10 从字符串获取整数示例

以下示例演示了如何使用 Integer valueOf(String s, int radix) 方法使用指定的包含 int 值的字符串获取 Integer 对象。我们创建了一个 String 变量并为其分配了一个 int 值。然后使用 valueOf() 方法,我们获取十进制等效值的 object 并打印它。

package com.tutorialspoint;
public class IntegerDemo {
   public static void main(String[] args) {
      String s = "170";
      System.out.println("String = " + s);
    
      /* returns the Integer object of the given string */
      System.out.println("valueOf = " + Integer.valueOf(s, 10));
   }
}

输出

让我们编译并运行上述程序,这将产生以下结果:

String = 170
valueOf = 170

使用基数 8 从字符串获取整数示例

以下示例演示了如何使用 Integer valueOf(String s, int radix) 方法使用指定的包含 int 值的字符串获取 Integer 对象。我们创建了一个 String 变量并为其分配了一个 int 值。然后使用 valueOf() 方法,我们获取八进制等效值的 object 并打印它。

package com.tutorialspoint;
public class IntegerDemo {
   public static void main(String[] args) {
      String s = "170";
      System.out.println("String = " + s);
    
      /* returns the Integer object of the given string */
      System.out.println("valueOf = " + Integer.valueOf(s,8));
   }
}

输出

让我们编译并运行上述程序,这将产生以下结果:

String = 170
valueOf = 120

使用基数 8 从十六进制字符串获取整数时遇到异常示例

以下示例演示了如何使用 Integer valueOf(String s) 方法使用指定的包含 int 值的字符串获取 Integer 对象。我们创建了一个 String 变量并为其分配了一个无效的 int 值。然后使用 valueOf() 方法,我们尝试获取对象并打印它。它将抛出 NumberFormatException。

package com.tutorialspoint;
public class IntegerDemo {
   public static void main(String[] args) {
      String s = "0x170";
      System.out.println("String = " + s);
    
      /* returns the Integer object of the given string */
      System.out.println("valueOf = " + Integer.valueOf(s,8));
   }
}

输出

让我们编译并运行上述程序,这将产生以下结果:

String = 0x170
Exception in thread "main" java.lang.NumberFormatException: For input string: "0x170"
	at java.lang.NumberFormatException.forInputString(Unknown Source)
	at java.lang.Integer.parseInt(Unknown Source)
	at java.lang.Integer.valueOf(Unknown Source)
	at com.tutorialspoint.IntegerDemo.main(IntegerDemo.java:11)
java_lang_integer.htm
广告

© . All rights reserved.