输入不正确,即使是正确的输入

xtupzzrd  于 2021-07-12  发布在  Java
关注(0)|答案(1)|浏览(297)

我对java还比较陌生,现在面临一些困难。所以我被要求运行一个程序,在这个程序中,你可以通过输入密码和学校名称登录到一个系统。每次尝试3次,直到有消息提示登录失败。我的问题是。一切正常,但在pin部分,(userinputpin==pin)部分,它会自动输入“尝试#2-输入学校名称-不正确”。第一次正确的尝试。当写下正确的学校名称时,当它应该通知您已经登录时,它也会显示登录失败。怎么了?
note:ignore comment,我来修。

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          
        }
jhdbpxl9

jhdbpxl91#

啊,是的,你这个扫描器。我无法告诉你我有多少次遇到同样的问题。
问题在于 nextInt() 函数有时将enter键视为另一个标记。因此,当您输入第一个值时,nextint()会识别输入的数字。但是在打印第二条消息之后,scanner对象中仍然存储了enter键。前进的唯一方法是清空对象,如下所示:

if(kb.hasNext()) kb.nextLine();

在每次输入数字后插入此项。

相关问题