In Java, reading console input is a fundamental task that allows your program to interact with the user. To read console input as an unsigned integer, you can leverage the built-in Scanner
class.
Using the Scanner Class
The Scanner
class provides a convenient way to read input from the console. Here's how you can use it to read an unsigned integer:
import java.util.Scanner;
public class ConsoleInputExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter an unsigned integer: ");
int unsignedInt = scanner.nextInt();
System.out.println("You entered: " + unsignedInt);
}
}
In the example above, we create a Scanner
object that reads input from the system console (System.in
). We then prompt the user to enter an unsigned integer and use the nextInt()
method to read the input and store it in the unsignedInt
variable.
It's important to note that the nextInt()
method will throw an InputMismatchException
if the user enters a non-integer value. To handle this, you can wrap the input reading in a try-catch
block:
import java.util.InputMismatchException;
import java.util.Scanner;
public class ConsoleInputExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int unsignedInt;
try {
System.out.print("Enter an unsigned integer: ");
unsignedInt = scanner.nextInt();
System.out.println("You entered: " + unsignedInt);
} catch (InputMismatchException e) {
System.out.println("Invalid input. Please enter an integer.");
}
}
}
By wrapping the input reading in a try-catch
block, you can gracefully handle cases where the user enters a non-integer value and provide an appropriate error message.
Remember, the nextInt()
method reads the input as a signed integer. If you need to ensure that the input is an unsigned integer, you'll need to perform additional validation, which will be covered in the next section.