Java Long.parseUnsignedLong(CharSequence, int, int, int)
方法
原文:https://www.studytonight.com/java-wrapper-class/java-long-parseunsignedlong-charsequence-int--method
Java parseUnsignedLong(CharSequence s, int beginText, int endText, int radix)
方法是java.lang
包的Long
类的一部分。在根据整数基数值解析传递的字符序列(从传递的起始索引开始,延伸到传递的(结束索引- 1 )后,此方法返回无符号长等价物。该方法没有采取措施防止CharSequence
在解析时发生变异。
语法:
public static long parseUnsignedLong(CharSequence s, int beginIndex, int endIndex, int radix)throws NumberFormatException
参数:
传递的参数是:
CharSequence s
:需要解析的字符序列。
int beginIndex
:开始解析的字符序列的索引。
int endIndex
:字符序列的索引,直到解析将扩展到的地方。
int radix
:传递字符序列所依据的整数值。
返回:
根据整数基数从开始索引开始,一直延伸到结束索引-1 ,返回解析字符序列后得到的等效无符号长值。
例外:
NullPointerException:
当输入字符为空时,出现此异常。
NumberFormatException
: 当输入字符序列不可解析时,出现此异常。
IndexOutOfBoundsException
:当开始索引为负,或者开始索引值大于结束索引值,或者结束索引值大于 s.length()时,会出现此异常。
例 1:
这里,返回解析后的字符序列的无符号长值。
import java.lang.Long;
public class StudyTonight {
public static void main(String[] args) throws NumberFormatException {
CharSequence s1 = "332";
CharSequence s2 = "442";
int radix = 8;
//returns the unsigned Long value of the entered string in accordance with the radix and beginning and end index
int res1 = Long.parseUnsignedLong(s1, 0, 1, radix);
System.out.println(res1);
int res2 = Long.parseUnsignedLong(s2, 0, 2, radix);
System.out.println(res2);
}
}
3 36
例 2:
这里有一个用户定义的例子,任何使用这段代码的人都可以输入自己选择的值,并获得等效的输出。
import java.lang.Long;
import java.util.Scanner;
public class StudyTonight {
public static void main(String[] args) {
try {
System.out.println("Enter value");
Scanner sc = new Scanner(System. in );
CharSequence s = sc.nextLine();
System.out.println("Enter radix");
int radix = sc.nextInt();
System.out.println("Enter start index");
int si = sc.nextInt();
System.out.println("Enter end index");
int ei = sc.nextInt();
//returns the unsigned Long value of the entered string in accordance with the radix and beginning and end index
int res = Long.parseUnsignedLong(s, si, ei, radix);
System.out.println(res);
}
catch(Exception e) {
System.out.println("Cannot parse this value");
}
}
}
输入值 501 输入基数 8 输入起始索引 0 输入结束索引 2 40
输入值 -45 输入基数 8 输入起始索引 0 输入结束索引 1 无法解析此值