Java Integer decode()方法

Java Integer decode()方法

人们经常看到,任何在(””)内的整数也被视为字符串,那么就需要将其解码为整数。 java.lang.Integer.decode() 方法的主要功能是将一个字符串解码成一个整数。该方法也接受十进制、十六进制和八进制的数字。

语法:

public static Integer decode(String str)
Java

参数: 该方法需要一个字符串数据类型的参数str,指的是需要解码的字符串。

返回值: 该方法返回一个Integer对象,该对象持有字符串str所代表的int值。

异常: 该方法抛出NumberFormatException,当String包含一个不能被解析的整数时。

例子

Input: str_value = "50"
Output: 50

Input: str_value = "GFG"
Output: NumberFormatException
Java

以下程序说明了java.lang.Integer.decode()方法。

程序1

// Java program to demonstrate working
// of java.lang.Integer.decode() method
import java.lang.*;
  
public class Gfg {
  
    public static void main(String[] args)
    {
  
        Integer int1 = new Integer(22);
        // string here given the value of 65
        String nstr = "65";
  
        // Returns an Integer object holding the int value
        System.out.println("Actual Integral Number = "+
        int1.decode(nstr));
    }
}
Java

输出。

Actual Integral Number = 65
Java

程序2: 当字符串值被传递时,会抛出NumberFormatException。

// Java program to demonstrate working
// of java.lang.Integer.decode() method
import java.lang.*;
  
public class Gfg {
  
    public static void main(String[] args)
    {
  
        Integer int1 = new Integer(22);
  
        // String here passed as "geeksforgeeks"
        String nstr = "geeksforgeeks";
  
        System.out.println("Actual Integral Number = ");
        System.out.println(int1.decode(nstr));
    }
}
Java

输出。

Exception in thread "main" java.lang.NumberFormatException: For input string: "geeksforgeeks"
    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 Gfg.main(Gfg.java:15)
Java

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册