Java Ineteger.decode()
方法
原文:https://www.studytonight.com/java-wrapper-class/java-integer-decode-method
Java decode()
方法属于Integer
类。decode()
方法用于将“”形式的字符串解码为整数。
可接受的数字有:
小数
十六进制的
八进制的
语法:
public static Integer decode(String s) throws NumberFormatException
参数:
该参数包括将被解码为整数的字符串。
返回:
字符串保存的整数对象的整数值。
如果字符串不包含任何可解析的整数,则抛出**NumberFormatException**
。
例 1:
这里,以“0”开头的数字将使用基数 8 解码为八进制,以“0x”开头的数字将使用基数 16 解码为十六进制,以“-0x”开头的数字将使用基数 16 解码为带符号的十六进制。
import java.lang.Integer;
public class StudyTonight
{
public static void main(String[] args)
{
Integer i = 30;
String s = "300";
System.out.println(Integer.decode("05234")); // decoding using base 8
System.out.println(Integer.decode("0x980")); // decoding using base 16
System.out.println(Integer.decode("-0x786")); // decode using base 16 signed
System.out.println(" Decoded Integer Number for the given string is = " +i.decode(s));
// returns the integer value of the Integer object which the String s holds.
}
}
2716 2432 -1926 给定字符串的解码整数为= 300
例 2:
在这里,我们遇到了NumberFormatException
,因为字符串 s 不能被解码成整数。
import java.lang.Integer;
public class StudyTonight
{
public static void main(String[] args)
{
Integer i = 100;
String s = "StudyTonight";
System.out.println(" Decoded integer number is = " + i.decode(s));
}
}
线程“main”Java . lang . numberformateexception 中的异常:对于输入字符串:“study night” 在 Java . lang . numberformateexception . For putstring(numberformateexception . Java:65) 在 Java . lang . integer . par sent(integer . Java:580) 在 Java . lang . integer . value of(integer . Java:740) 在 Java . lang . integer . decode(integer . Java:1197) 在 study night . main(study night . Java:T0)
例 3:
这里有一个通用的例子,用户可以输入他选择的数字并获得所需的输出。try
和catch
块用于处理程序执行期间发生的任何异常。
import java.lang.Integer;
import java.util.Scanner;
public class StudyTonight
{
public static void main(String[] args)
{
try
{
System.out.print("Enter the string to be decoded: ");
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
Integer decoded = Integer.decode(s);
System.out.println("Decoded value is:" + decoded);
}
catch(Exception e)
{
System.out.println("Number Format Exception,Please Check the Entered String");
}
}
}
输入需要解码的字符串:-0x567 解码值为:-1383
- *输入需要解码的字符串: 今晚学习 数字格式异常,请检查输入的字符串
实时示例:
在这里,您可以测试实时代码示例。您可以为不同的值执行示例,甚至可以编辑和编写您的示例来测试 Java 代码。