当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。