Introduction
In this lab, you will learn about the parseUnsignedInt method present in the Integer class of the java.lang package. This method helps to parse the character sequence into an unsigned integer value.
Create a Java file
Create a new Java file with the name ParseUnsignedIntLab.java in the ~/project directory using the following command:
touch ~/project/ParseUnsignedIntLab.java
Import package and Define Class
Import the required java.util and java.lang packages and define the ParseUnsignedIntLab class.
import java.util.Scanner;
import java.lang.Integer;
public class ParseUnsignedIntLab {
public static void main(String[] args) {
}
}
Read input from user
Use Scanner class to read input from the user and store it into a String named text. Then, read the radix and start (beginIndex) and end (endIndex) indices of the substring from the user.
Scanner sc = new Scanner(System.in);
System.out.print("Enter a character sequence: ");
String text = sc.nextLine();
System.out.print("Enter the integer radix: ");
int radix = sc.nextInt();
System.out.print("Enter the start index: ");
int beginIndex = sc.nextInt();
System.out.print("Enter the end index: ");
int endIndex = sc.nextInt();
Parse the character sequence
Use the parseUnsignedInt method to parse the substring of the given character sequence with the given radix.
int result = Integer.parseUnsignedInt(text, beginIndex, endIndex, radix);
System.out.println("Unsigned integer value: " + result);
Handle exceptions
Handle the exceptions with try-catch blocks.
try {
int result = Integer.parseUnsignedInt(text, beginIndex, endIndex, radix);
System.out.println("Unsigned integer value: " + result);
} catch (NumberFormatException e) {
System.out.println("Cannot parse the input string");
} catch (IndexOutOfBoundsException e) {
System.out.println("The start or end index is invalid");
}
Compile and run the program
Compile the program using the following command:
javac ParseUnsignedIntLab.java
Run the program using the following command:
java ParseUnsignedIntLab
Summary
In this lab, you have learned about the parseUnsignedInt method present in the Integer class of the java.lang package. You have learned to use this method to parse a character sequence into an unsigned integer value. Additionally, you have learned to handle exceptions in case of incorrect input or invalid indices values were provided.



