當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Java Short decode()用法及代碼示例

Java Short 類的 decode() 方法用於將字符串解碼為 Short。它接受十進製、十六進製和八進製數。如果我們在字符串中放置其他內容,則此方法將拋出異常。

用法

public static Short decode(String x) throws NumberFormatException

參數

X:將被解碼為 Short 的編碼字符串。

異常

如果輸入參數 "String x" 不包含可解析的 short 則它將拋出以下異常:throws NumberFormatException

返回值

decode() 方法將返回持有由 X 表示的短值的 Short 對象。

示例 1:(字符串輸入中的十進製數)

public class ShortDecodeExample1 { 
public static void main(String[] args) {      //String value   
String decimalValue = "38"; //Decimal number system   //String Value decoding into Short   
Short dec = Short.decode(decimalValue);   
System.out.println("decoded String value in to Short  = " + dec);  
}  
}

輸出:

decoded String value in to Short  = 38 

示例2:(字符串輸入中的八進製數)

public class ShortDecodeExample2 { 
public static void main(String[] args) {   //Octal number system to write 5   
String decimalValue = "008";    //String Value decoding into Short   
Short dec = Short.decode(decimalValue);   
System.out.println("decoded String value in to Short  = " + dec);  
} 
}

輸出:

decoded String value in to Short  = 8 

示例 3:(字符串輸入中的十六進製數)

public class DecodeExample3 { 
public static void main(String[] args) {   //Hexa number system to write 15   
String decimalValue = "0x0F";    //String Value decoding into Short   
Short dec = Short.decode(decimalValue);   
System.out.println("decoded String value in to Short  = " + dec);  } }

輸出:

decoded String value in to Short  = 15 

例4:(輸入錯誤,會拋出異常)

public class DecodeExample4{ 
public static void main(String[] args) {   //Wrong input, it will throw Exception   
String decimalValue = "hello";    //String Value decoding into Short   
Short dec = Short.decode(decimalValue);   
System.out.println("decoded String value in to Short  = " + dec);  }}

輸出:

java.lang.NumberFormatException 






相關用法


注:本文由純淨天空篩選整理自 Java Short decode() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。