Java Long.decode()方法

原文:https://www.studytonight.com/java-wrapper-class/java-long-decode-method

Java decode()方法属于Long类。decode()方法用于将一串形式“”解码为一个长。

可接受的数字有:

  • 小数

  • 十六进制的

  • 八进制的

语法:

public static Long decode(String nm) throws NumberFormatException

参数:

该参数包括将被解码为长的字符串 nm。

返回:

字符串 nm 包含的 long 对象的长值。

如果字符串不包含任何可解析的长度,则抛出NumberFormatException

例 1:

这里,以“0”开头的数字将使用基数 8 解码为八进制,以“0x”开头的数字将使用基数 16 解码为十六进制,以“ -0x 开头的数字将使用基数 16 解码为带符号十六进制。

import java.lang.Long;
public class StudyTonight
{  
    public static void main(String[] args)
    {          
        Long i = 30L; 

        String s = "300";    

        System.out.println(Long.decode("05234"));   // decoding using base 8             

        System.out.println(Long.decode("0x980"));   // decoding using base 16               

        System.out.println(Long.decode("-0x786"));  // decode using base 16 signed 

        System.out.println(" Decoded Long Number for the given string is = " +i.decode(s)); 
        // returns the long value of the Long object which the String s holds.
    }  
}

2716 2432 -1926 给定字符串的解码长数字为= 300

例 2:

在这里,我们遇到了NumberFormatException ,因为字符串 s 不能被解码成长的。

import java.lang.Long;
public class StudyTonight
{  
    public static void main(String[] args)
    {  
        Long i = 100L;          
        String s = "StudyTonight";             
        System.out.println(" Decoded long number is = " + i.decode(s));   
    }  
}

线程“main”Java . lang . numberformateexception 中的异常:对于输入字符串:“StudyTonight”在 Java . lang . numberformateexception . For putstring(numberformateexception . Java:65) 在 Java . lang . long . parselong(long . Java:589) 在 Java . lang . long . value of(long . Java:776) 在 Java . lang . long . decode(long . Java:928) 在 study night . main(study night . Java:8)

例 3:

这里有一个通用的例子,用户可以输入他选择的数字并获得所需的输出。trycatch块用于处理程序执行期间发生的任何异常。

import java.lang.Long;
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();  
            Long decoded = Long.decode(s);  
            System.out.println("Decoded value is:" + decoded);  
        }
        catch(Exception e)
        {
            System.out.println("Number Format Exception,Please Check the Entered String");
        }
    }  
}

输入需要解码的字符串:0x6745 解码值为:26437

                                                    • 输入需要解码的字符串:-0x587 解码值为:-1415 **输入需要解码的字符串:mohit 数字格式异常,请检查输入的字符串

实时示例:

在这里,您可以测试实时代码示例。您可以为不同的值执行示例,甚至可以编辑和编写您的示例来测试 Java 代码。