We can also read input from the console and parse it as an unsigned integer. Here's an example:
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
String s = scanner.nextLine();
try {
int n = Integer.parseUnsignedInt(s); //Converts the passed string as unsigned integer
System.out.println(n);
} catch(NumberFormatException ex) {
System.out.println("Invalid input.");
}
In this code, we are using the Scanner
class to read input from the console. We are then parsing the input string as an unsigned integer using the parseUnsignedInt()
method. Finally, we are catching any exceptions that may occur while parsing the input.
To run this code in the terminal, we need to first compile it using the command:
javac UnsignedIntegerParser.java
Then, we can run it using the command:
java UnsignedIntegerParser