Validating User Input into Integers using Scanner
When developing robust programs, handling user input confidently is critical. Consider the scenario where you require the user to enter two integers, with the second integer greater than the first. Additionally, you want to gracefully handle invalid input, such as characters instead of numbers.
To achieve this, you can utilize the hasNextInt() method provided by the Scanner class. This method returns true if the next token in the input can be interpreted as an int value using the nextInt() method. Here's how you can use it:
Scanner sc = new Scanner(System.in); System.out.print("Enter number 1: "); // Loop until a valid int is entered while (!sc.hasNextInt()) { sc.next(); // Consume the invalid input } int num1 = sc.nextInt(); int num2; System.out.print("Enter number 2: "); do { // Loop until a valid int greater than num1 is entered while (!sc.hasNextInt()) { sc.next(); // Consume the invalid input } num2 = sc.nextInt(); } while (num2 < num1); System.out.println(num1 + " " + num2);
By using hasNextInt() and looping accordingly, you ensure that the input is a valid integer and meets your criteria.
The above is the detailed content of How Can I Validate User Integer Input and Ensure the Second Integer is Greater Than the First?. For more information, please follow other related articles on the PHP Chinese website!