Java - Integer valueOf(String s) 方法



描述

Java Integer valueOf(String s) 方法返回一個 Integer 物件,其中包含指定字串 s 的值。

宣告

以下是 java.lang.Integer.valueOf() 方法的宣告

public static Integer valueOf(String s) throws NumberFormatException

引數

s − 這是要解析的字串。

返回值

此方法返回一個 Integer 物件,該物件包含字串引數表示的值。

異常

NumberFormatException − 如果字串無法解析為整數。

從包含正整數的字串中獲取 Integer 的示例

以下示例演示瞭如何使用 Integer valueOf(String s) 方法,透過包含整數值的指定字串來獲取 Integer 物件。我們建立了一個字串變數併為其分配了一個正整數的值。然後使用 valueOf() 方法獲取物件並列印它。

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));
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

String = 170
valueOf = 170

從包含負整數的字串中獲取 Integer 的示例

以下示例演示瞭如何使用 Integer valueOf(String s) 方法,透過包含整數值的指定字串來獲取 Integer 物件。我們建立了一個字串變數併為其分配了一個負整數的值。然後使用 valueOf() 方法獲取物件並列印它。

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));
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

String = -170
valueOf = -170

從包含八進位制值的字串中獲取 Integer 時遇到異常的示例

以下示例演示瞭如何使用 Integer valueOf(String s) 方法,透過包含無效整數值的指定字串來獲取 Integer 物件。我們建立了一個字串變數併為其分配了一個無效整數的值。然後使用 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));
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

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