Home > Java > javaTutorial > How Can I Validate User Integer Input and Ensure the Second Integer is Greater Than the First?

How Can I Validate User Integer Input and Ensure the Second Integer is Greater Than the First?

Linda Hamilton
Release: 2024-12-12 13:11:11
Original
919 people have browsed it

How Can I Validate User Integer Input and Ensure the Second Integer is Greater Than the First?

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);
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template