我对 Java 还很陌生,我遇到了一些困难。因此,我被指示运行一个程序,您可以通过输入密码和学校名称来登录系统。每次您可以尝试 3 次,直到出现一条消息提示您登录失败。我的问题是。一切都很好,但在 PIN 部分、(userInputPin==PIN) 部分,它会自动输入“尝试#2 - 输入您的学校名称 - 不正确。”第一次正确尝试时。当写入正确的学校名称时,它也会显示登录失败,而它应该通知您已登录。错误是什么?
注意:忽略评论,我会修复它们。
public class Login {
public static final int PIN = 1234; //Declaring constant for fixed PIN
//Declaring constant for first school name
public static final String FIRST_SCHOOL = "St. Charles";
public static void main(String[] args) {
Scanner kb = new Scanner (System.in); //Declaring scanner object
int attempts = 1; //Declaring variable for attempt number
//Printing first paragraph section of the program
System.out.println("This program simulates logging into a bank account,"
+ "\nasking certain questions for security.\n");
// PIN Section
while(attempts<=3) //While loop
{
System.out.print("Attempt #"+attempts+" - Enter PIN: ");
int userInputPin = kb.nextInt(); //User inputs pin number
//Conditional situations
if(userInputPin==PIN)
{
attempts=1;
while(attempts<=3)
{
System.out.print("\nAttempt #"+ attempts+" - Enter your first school: ");
String userInputSchool = kb.next();
//Conditional situations
if(userInputSchool.equals(FIRST_SCHOOL))
{
System.out.println("\nYou're logged in.");
}
else{
if(attempts==3)
{
System.out.println("\nLogin failed.");
}
else
{
System.out.println("Incorrect.\n");
}
}
attempts++;
}
}
else{
if(attempts==3){
System.out.println("\nLogin failed.");
}
else{
System.out.println("Incorrect.\n");
}
}
attempts++; //Increments attempt by 1 when PIN is incorrect
}
最佳答案
啊,是的,你这个扫描仪。我无法告诉你我遇到过多少次同样的问题。
问题在于 nextInt()
函数有时会将 Enter 键视为另一个标记。因此,当您输入第一个值时,nextInt() 会识别输入的数字。但在打印第二条消息后,扫描仪对象中仍然存储有回车键。前进的唯一方法是清空对象,如下所示:
if(kb.hasNext()) kb.nextLine();
每次输入数字后插入此内容。
关于java - 尽管输入正确,但输入不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60213697/