Reputation: 27
I have no idea why my scanner for the staffID and staffPassword is not working after I choose to continue typing a new record.
Click to see the output of the code
public class Test {
public static void main(String args[]){
String staffID, staffPassword; //Staff Record Variable
int a = 0;
boolean validation;
Staff[] staff = new Staff[1000];
int staffCount = 0;
Scanner input = new Scanner(System.in);
do{
staff[staffCount] = new Staff();
System.out.print("Staff ID: ");
staffID = input.nextLine();
staff[staffCount].SetStaffID(staffID);
System.out.print("Password: ");
staffPassword = input.nextLine();
staff[staffCount].SetPassword(staffPassword);
System.out.println("\nEnter 1 to continue, enter 2 to stop.");
System.out.print("Continue to add more record?(1 or 0): " );
a = input.nextInt();
}while(a == 1);
}
}
Upvotes: 2
Views: 84
Reputation: 1860
This is because the nextInt()
method doesn't consume the new line after hitting enter for the a
variable. It's better to leave the nextLine()
in its place because the next()
works until it reach a delimiter (default white space). What does that mean? It means that if you're trying to set the staffID
with next()
like this : "Id For Staff", the actual staffID
will be just "Id".
Instead of changing nextLine()
to next()
I suggest you to use a simple input.nextLine()
after the last line of your do while
(a = input.nextInt();
)
Upvotes: 0