Java - Short decode() 方法



Java Short decode() 方法將字串轉換為短整型。它接受十進位制、十六進位制和八進位制數字,遵循以下語法:

可解碼字串 -

  • Signopt DecimalNumeral

  • Signopt 0x HexDigits

  • Signopt 0x HexDigits

  • Signopt # HexDigits

  • Signopt 0 OctalDigits

Short.parseShort 方法根據指定的基數 (10、16 或 8) 解析可選符號和/或基數說明符 ("0x"、"0X"、"#" 或前導零) 後的字元序列。除非此字串表示正值,否則將引發 NumberFormatException。如果負號出現在提供的字串的第一個字元中,則結果將被取反。字串不能包含任何空格字元。

語法

以下是Java Short decode() 方法的語法:

public static Short decode(String nm) throws NumberFormatException

引數

  • nm - 這是要解碼的字串。

返回值

此方法返回一個 Short 物件,其中包含 nm 表示的短整型值。

解碼包含正短整型值的字串示例

當將正整數作為引數傳遞給此方法時,它將返回相同的值。

以下是一個示例,透過將正整數作為字串引數傳遞給建立的變數 'x' 來將字串值解碼為短整型:

package com.tutorialspoint;

public class ShortDemo {
   public static void main(String[] args) {
      String x = "87";
      Short decode = Short.decode(x);
      System.out.println("String value decoded to short is:  = " + decode);
   }
}

輸出

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

String value decoded to short is:  = 87

解碼包含正短整型八進位制值的字串示例

當我們將八進位制數作為引數傳遞給此方法時,它將返回等效的解碼字串值到短整型。

在下面的示例中,建立了字串變數 'x'。然後將八進位制值賦給此變數。之後,透過傳遞字串引數中的八進位制數將其解碼為短整型:

package com.tutorialspoint;

public class ShortDemo {
   public static void main(String[] args) {
      String x = "072";
      Short decode = Short.decode(x);
      System.out.println("decoded String value in to Short  = " + decode);
   }
}  

輸出

以下是上述程式碼的輸出:

decoded String value in to Short  = 58

解碼包含正短整型十六進位制值的字串示例

如果我們將十六進位制數作為引數傳遞,則此方法將返回等效的解碼字串值到短整型。

以下是一個示例,其中建立了一個字串變數 'x'。將十六進位制數賦給該變數。然後,為了將字串值解碼為短整型,將十六進位制數作為字串引數傳遞:

package com.tutorialspoint;

public class ShortDemo {
   public static void main(String[] args) {
      String x = "0x6f";
      Short decode = Short.decode(x);
      System.out.println("decoded String value in to Short  = " + decode);
   }
}

輸出

執行上述程式後,輸出如下:

decoded String value in to Short  = 111

解碼包含無效值的字串時遇到異常示例

當我們使用此方法傳遞字串作為引數時,它將返回 NumberFormatException。

在下面的示例中,賦給字串變數 'x' 的值 "TutorialsPoint" 不包含可解析的短整型值。因此,它會丟擲 NumberFormatException:

package com.tutorialspoint;

public class ShortDemo {
   public static void main(String[] args) {
      String x = "TutorialsPoint";
      Short decode = Short.decode(x);
      System.out.println("decoded String value in to Short  = " + decode);
   }
}

NumberFormatException

執行上述程式碼時,我們得到以下輸出:

Exception in thread "main" java.lang.NumberFormatException: For input string: "TutorialsPoint"
      at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
      at java.base/java.lang.Integer.parseInt(Integer.java:668)
      at java.base/java.lang.Integer.decode(Integer.java:1454)
      at java.base/java.lang.Short.decode(Short.java:326)
      at com.tutorialspoint.ShortDemo.main(ShortDemo.java:4)
java_lang_short.htm
廣告