This program asks the user to input their student id number which must be an integer between 0-999999. The testID method that has been commented out uses a do while loop with an inner while loop that ensures only integer values are input by the user. This method works without any issues.
While trying to rewrite the code (second testID method) every time I run the program and type in a string or char value I get an inputMismatchException
. This doesn't happen with the first method. Can someone please explain why this is happening?
import java.util.*;
public class StudentID{
public static int studentID= -1;
public static Scanner input = new Scanner(System.in);
public static void main(String[] args){
testID();
}
/*
public static void testID(){
System.out.println("Enter your Student EMPLID (0-999999):");
do{
while (!input.hasNextInt()){
input.nextLine();
System.out.println("Enter a valid Student EMPLID (0-999999).");
}
studentID = input.nextInt();
if(0 > studentID || studentID > 999999){
input.nextLine();
System.out.println("Enter a valid Student EMPLID (0-999999).");
}
} while (0 > studentID || studentID > 999999);
System.out.println("Student EMPLID: " + studentID);
}
*/
public static void testID(){
System.out.println("Enter your Student EMPLID (0-999999:)");
while ((!input.hasNextInt()) && (0 > studentID) && (studentID > 999999)){
input.nextLine();
System.out.println("Enter a valid Student EMPLID (0-999999:)");
}
studentID = input.nextInt();
System.out.println("Student EMPLID: " + studentID);
}
}