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


Java Long decode()用法及代码示例


java.lang.Long.decode()是Java中的内置函数,可将String解码为Long。它接受十进制,十六进制和八进制数字。

用法:

public static Long decode(String number) throws NumberFormatException 

Parameter:
number-  the number that has to be decoded into a Long. 

错误和异常:


  • NumberFormatException:如果字符串不包含可分析的long,则程序将返回此错误。

返回值:它返回解码后的字符串。

程序1:下面的程序演示了函数的工作。

// Java program to demonstrate 
// of java.lang.Long.decode() method 
import java.lang.Math; 
  
class GFG { 
  
    // driver code 
    public static void main(String args[]) 
    { 
  
        // demonstration of function 
        Long l = new Long(14); 
        String str = "54534"; 
  
        System.out.println("Number = "
                        + l.decode(str)); 
    } 
}

输出:

Number = 54534 

程序2:该程序演示了使用decode()函数进行的转换

// Java program to demonstrate 
// of java.lang.Long.decode() method 
import java.lang.Math; 
  
class GFG { 
  
    // driver code 
    public static void main(String args[]) 
    { 
        // demonstration of conversions 
        String decimal = "10"; // Decimal 
        String hexa = "0XFF"; // Hexa 
        String octal = "067"; // Octal 
  
        // convert decimal val to number using decode() method 
        Integer number = Integer.decode(decimal); 
        System.out.println("Decimal [" + decimal + "] = " + number); 
  
        number = Integer.decode(hexa); 
        System.out.println("Hexa [" + hexa + "] = " + number); 
  
        number = Integer.decode(octal); 
        System.out.println("Octal [" + octal + "] = " + number); 
    } 
}

输出:

Decimal [10] = 10
Hexa [0XFF] = 255
Octal [067] = 55

程序3:该程序演示错误和异常。

// Java program to demonstrate 
// of java.lang.Long.decode() method 
import java.lang.Math; 
  
class GFG { 
  
    // driver code 
    public static void main(String args[]) 
    { 
        // demonstration of errorand exception when 
        // a non-parsable Long is passed 
  
        String decimal = "1A"; 
  
        // throws an error 
        Integer number = Integer.decode(decimal); 
        System.out.println("string [" + decimal + "] = " + number); 
    } 
}

输出:

 
Exception in thread "main" java.lang.NumberFormatException:For input string:"1A"
    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(File.java:16)



相关用法


注:本文由纯净天空筛选整理自gopaldave大神的英文原创作品 Java Long decode() method with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。