Java Long.parseUnsignedLong(String,int)方法

原文:https://www.studytonight.com/java-wrapper-class/java-long-parseunsignedlongstring-s-int-radix-method

Java parseUnsignedLong(String s,int radix)方法是java.lang包的Long类的一部分。此方法用于将字符串值解析为作为参数传递的指定整数基数值中的无符号十进制 Long 对象。

必须注意的是,除了用于定义整数符号的第一个字符之外,字符串中传递的字符必须都是十进制的。ASCII 加号“+”用于描述正值。

语法:

public static long parseUnsignedLong(String s, int radix)

参数:

传递的参数是要返回其无符号十进制 Long 对象的字符串值和将根据其解析输入字符串的整数基数值。

例外:

NumberFormatException : 当输入字符串不可解析时,会出现此异常。

返回:

根据基数值,返回作为参数传递的String值的无符号十进制Long对象的值。

例 1:

这里,无符号十进制Long对象表示根据传递的整数基数返回String值。

import java.lang.Long;

public class StudyTonight {
  public static void main(String[] args) throws NumberFormatException {
    String s1 = "603";
    String s2 = "834";
    int radix = 16;
    System.out.print("\nEntered value and Base value is: " + s1 + " and " + radix);
    //returns the unsigned Long object of the entered string in accordance with the radix            
    System.out.println("\nEquivalent Long object is " + Long.parseUnsignedLong(s1, radix));

    System.out.print("\nEntered value and Base value is: " + s2 + " and " + radix);
    //returns the unsigned Long object of the entered string in accordance with the radix            
    System.out.println("\nEquivalent Long object is " + Long.parseUnsignedLong(s2, radix));
  }
}

输入值和基础值为:603 和 16 等效长对象为 1539

输入值和基础值为:834 和 16 等效长对象为 2100

例 2:

这里有一个用户定义的例子,任何使用这段代码的人都可以输入自己选择的值,并获得等效的输出。

import java.util.Scanner;

public class StudyTonight {
  public static void main(String[] args) {
    try {
      System.out.print("Enter the value: ");
      Scanner sc = new Scanner(System. in );
      String s = sc.nextLine();
      System.out.print("Enter the radix: ");
      int radix = sc.nextInt();
      System.out.println("Equivalent Long object : " + Long.parseUnsignedLong(s, radix)); //parse the string value into unsigned value with respect to radix 
    }
    catch(NumberFormatException e) {
      System.out.println("Invalid Input!!");
    }
  }
}

输入数值:645 输入基数:8 等效长对象:421

                                                                              • T4】输入数值:897 输入基数:16 等效长对象:2199 *输入数值:0x44 输入基数:8 无效输入!!

实时示例:

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