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
廣告