Java Integer.parseUnsignedInt(String,int)方法

原文:https://www.studytonight.com/java-wrapper-class/java-integer-parseunsignedint-string-int-method

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

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

语法:

public static int parseUnsignedInt (String s, int radix)

参数:

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

例外:

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

返回:

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

例 1:

这里,根据传递的整数基数,返回字符串值的无符号十进制整数表示。

import java.lang.Integer;

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 Integer object of the entered string in accordance with the radix            
            System.out.println("\nEquivalent Integer object is " + Integer.parseUnsignedInt(s1, radix)); 

            System.out.print("\nEntered value and Base value is: " + s2 + " and " + radix);  
           //returns the unsigned Integer object of the entered string in accordance with the radix            
            System.out.println("\nEquivalent Integer object is " + Integer.parseUnsignedInt(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 Integer object : " +Integer.parseUnsignedInt(s,radix)); //parse the string value into unsigned value with respect to radix 
        }
        catch(NumberFormatException e)
        {
          System.out.println("Invalid Input!!");
        }  
    }  
}

输入数值:744 输入基数:16 等效整数对象:1860

                                                                      • T4】输入数值:-234 输入基数:8 无效输入!!

实时示例:

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