[英]After running the DO WHILE loop, scanner is not working
I have no idea why my scanner for the staffID and staffPassword is not working after I choose to continue typing a new record.我不知道为什么在我选择继续输入新记录后,我的员工 ID 和员工密码扫描仪不起作用。
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);
}
}
使用input.next()
而不是input.nextLine()
This is because the nextInt()
method doesn't consume the new line after hitting enter for the a
variable.这是因为
nextInt()
方法在为a
变量按下回车键后不会使用新行。 It's better to leave the nextLine()
in its place because the next()
works until it reach a delimiter (default white space).最好将
nextLine()
留在nextLine()
处,因为next()
一直工作,直到它到达分隔符(默认空格)。 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".这意味着,如果你想设置
staffID
与next()
是这样的:“ID为员工”的实际staffID
将只是“身份证”。
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();
)我建议您不要将
nextLine()
更改为next()
我建议您在do while
的最后一行之后使用一个简单的input.nextLine()
( a = input.nextInt();
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.