I'm having an issue with Scanner in that it seems to be taking the input value type and forcing the next time the user inputs a value to be of the same type. I cannot find any reason why this code is not working and gives me an InputMismatchException as I have written code like this a million times and not had problems.
public void register(){
Scanner input=new Scanner(System.in);
System.out.println("What course would you like to register for?");
String course_name = input.next();
System.out.println("What section?");
int section = input.nextInt();
for (int i = 0; i < courses.size(); i++) {
if (courses.get(i).getCourse_name().equals(course_name)) {
if (courses.get(i).getCourse_section() == section) {
courses.get(i).AddStudent(this.first_name+" "+this.last_name);
}
}
}
input.close();
}
This problem is not just for the register() method, but program-wide, eg with this code:
public void Options() {
Scanner input=new Scanner(System.in);
while (true) {
System.out.println("What would you like to do (Enter corresponding number):" + "\n" + "1) View all courses" + "\n" + "2) View all courses that are not full" + "\n" + "3) Register on a course" + "\n" + "4) Withdraw from a course" + "\n" + "5) View all courses that the current student is being registered in" + "\n" + "6) Exit");
int user = input.nextInt();
if (user == 1)
viewAll();
if (user == 2)
viewAllOpen();
if (user == 3)
register();
if (user == 4)
withdraw();
if (user == 5)
viewRegistered();
if (user == 6) {
Serialize();
break;
}
}
If one of the methods, such as register required the user to enter a String, the int user=input.nextInt(); will cause an InputMismatchException.