Java Integer decode() 方法

2025 年 3 月 25 日 | 阅读 2 分钟

decode() 方法是 java.lang 包下 Integer 类的静态方法。该方法的主要作用是将以 (" ") 形式书写的字符串解码为整数

decode() 方法还接受十进制、十六进制和八进制数。它由以下语法给出

可解码字符串

Signopt DecimalNumeral
Signopt 0x HexDigits
Signopt 0X HexDigits
Signopt # HexDigits
Signopt 0 OctalDigits

符号

这种类型的字符串将抛出 NumberFormatException 或表示一个 值。如果可解码字符串的第一个字符是负号,则结果会被取反。字符串中不允许出现空格字符。

语法

以下是 decode() 方法的声明

参数

数据类型参数描述必需/可选
Stringnm我们想将其解码为 Integer 对象的字符串值必需

返回值

decode() 方法返回一个 Integer 对象,该对象保存由字符串 nm 表示的 int 值。

异常

NumberFormatException - 如果字符串不包含可以解析的整数,则此方法会抛出异常。

兼容版本

Java 1.2 及以上版本

示例 1

输出

81
276
-260

示例 2

输出

Integer Number is = 555

示例 3

这是一个例子,其中我们传递了字符串值,它显示了 NumberFormatException。

输出

Exception in thread "main"java.lang.NumberFormatException: For input string: "JavaTpoint"
	at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
	at java.lang.Integer.parseInt(Integer.java:580)
	at java.lang.Integer.valueOf(Integer.java:740)
	at java.lang.Integer.decode(Integer.java:1197)
	at myPackage.DecodeMethodExample.main(DecodeMethodExample.java:8)

示例 4

输出

Enter a value to decode: 656
Result:656