Reputation: 17
What I'm trying to do is allow the user to enter a first name and a surname. The user is allowed to enter a first name with no issue but as soon as space is hit and their surname is entered, it gives me the error mentioned in the title.
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int choice,
String name, stuNum;
do
{
System.out.println("");
System.out.println("Student Grade System");
System.out.println("----------------------\n");
System.out.println(" 1) Enter student details");
System.out.println(" 2) Display student grades");
System.out.println(" 3) Display student statistics");
System.out.println(" 4) Display full transcript");
System.out.println(" 0) Exit System\n");
System.out.print("Select an option [0-4] >> ");
choice = sc.nextInt();
System.out.println("");
switch(choice)
{
case 1:
System.out.println("Entering Student Details");
System.out.println("------------------------");
System.out.print(" Student name: ");
name = sc.next(); //somewhere here it messes up
System.out.print(" Student number: ");
stuNum = sc.next();
}
}while(choice !=0);
}
This is the bare minimum of my code as I am just starting to write it but this issue is preventing me from going further. I've already tried using sc.nextLine(); and changing the variable stuNum to an int variable. Neither works. The full error it gives is as follows:
java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:840)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextInt(Scanner.java:2091)
at java.util.Scanner.nextInt(Scanner.java:2050)
at Project.main(Project.java:40)
Upvotes: 0
Views: 131
Reputation: 1419
This is because sc.next()
will not consume the space. So it will read the next token (in this case the lastname after the space) instead of the next thing entered. Try for yourself: when you put in a name enter Firstname 1
and it will enter student number 1 automatically. Use Scanner's nextLine()
method to consume the entire line.
You can parse your int choice with Integer.parseInt(sc.nextLine());
Upvotes: 0
Reputation: 4609
Use extra nextLine to flush the scanner buffer after you have taken students name
switch(choice)
{
case 1:
System.out.println("Entering Student Details");
System.out.println("------------------------");
System.out.print(" Student name: ");
name = sc.nextLine(); //somewhere here it messes up
sc.nextLine(); // to clean the enter key stored in the buffer
System.out.print(" Student number: ");
stuNum = sc.nextLine();
}
Upvotes: 0
Reputation: 27
Using next() will only return what comes before a space.That means It won't consume a space. but nextLine() automatically moves the scanner down after returning the current line. So, just replace next() with nextline() in your code.
Upvotes: 1