JoN
JoN

Reputation: 55

Using while loop to check input but it runs twice from the second time

I use the while loop to check if the input is an integer or not, the first time encounter a wrong type, it works fine, execute the statements in the loop once. But from the second time, it runs the statements in the loop twice. I already use sc.nextLine() to clear the previous input, still....

Pls ignore it is a date that i need to get in this case, I understand there are other methods to get a date, assume it is an integer the program need later. What I want to know is what is causing the loop to run twice from the second time before taking a new input? And how to avoid this? Thanks

I can copy the whole program if needed, but it seems a bit long... It is the getInput() method with the problem:

import java.util.Scanner;

public class DayOfWeek {

    static Scanner sc = new Scanner(System.in);
    static int day, month, year;

    public static void main(String[] args) {

            System.out.println("");
            System.out.print("Please enter the DAY in numeric form: ");
            day = getInput();
            System.out.print("Please enter the MONTH in numeric form: ");
            month = getInput();
            System.out.print("Please enter the YEAR in numeric form: ");
            year = getInput();

    }

    public static int getInput() {
    while (!sc.hasNextInt()) {
        sc.nextLine();
        System.out.print("Please enter integer only. Try again: ");
    }
    return sc.nextInt();
    }
}

this is the result on the console :

Please enter the DAY in numeric form: a
Please enter integer only. Try again: 1
Please enter the MONTH in numeric form: b
Please enter integer only. Try again: Please enter integer only. Try again: 1
Please enter the YEAR in numeric form: c
Please enter integer only. Try again: Please enter integer only. Try again: 

Upvotes: 3

Views: 1356

Answers (1)

Alex
Alex

Reputation: 803

Because after it reads the integer value, it will leave the [ENTER] from System.in. And when you start the next getInput(), [ENTER] is tested by sc.hasNextInt() and return false. So it will loop twice for the second and third round of input.

Try modify your method as below. It will discard anything user input after the 1st integer for each round of input.

    public static int getInput() {
        while (!sc.hasNextInt())
        {
            sc.nextLine();
            System.out.print("Please enter integer only. Try again: ");
        }
        int result = sc.nextInt();
        sc.nextLine();
        return result;
    }

Upvotes: 1

Related Questions