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: