Java - Short valueOf(String s) 方法



描述

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

宣告

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

public static Short valueOf(String s) throws NumberFormatException

引數

s - 要解析的字串。

返回值

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

異常

NumberFormatException - 如果字串無法解析為 short 型別。

使用帶正 short 值的字串獲取 Short 物件示例

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

package com.tutorialspoint;

public class ShortDemo {
   public static void main(String[] args) {
      String s = "170";
      System.out.println("String = " + s);
    
      /* returns the Short object of the given string */
      System.out.println("valueOf = " + Short.valueOf(s));
   }
}

輸出

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

String = 170
valueOf = 170

使用帶負 short 值的字串獲取 Short 物件示例

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

package com.tutorialspoint;

public class ShortDemo {
   public static void main(String[] args) {
      String s = "-170";
      System.out.println("String = " + s);
    
      /* returns the Short object of the given string */
      System.out.println("valueOf = " + Short.valueOf(s));
   }
}

輸出

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

String = -170
valueOf = -170

使用無效值的字串獲取 Short 物件時遇到異常的示例

以下示例演示瞭如何使用 Short valueOf(String s) 方法,使用包含 short 值的指定字串獲取 Short 物件。我們建立了一個 String 變數併為其分配了一個無效的 short 值。然後使用 valueOf() 方法嘗試獲取物件並列印它。它將丟擲 NumberFormatException 異常。

package com.tutorialspoint;

public class ShortDemo {
   public static void main(String[] args) {
      String s = "0x170";
      System.out.println("String = " + s);
    
      /* returns the Short object of the given string */
      System.out.println("valueOf = " + Short.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.Short.parseShort(Unknown Source)
	at java.lang.Short.valueOf(Unknown Source)
	at java.lang.Short.valueOf(Unknown Source)
	at com.tutorialspoint.ShortDemo.main(ShortDemo.java:11)
java_lang_short.htm
廣告

© . All rights reserved.