java - 尽管输入正确,但输入不正确

标签 java netbeans while-loop

我对 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/

相关文章:

java - 为什么我不能在 SecurityManager 下关闭我自己的 ExecutorService?

java - 如何为 Java 更改 TTS 的声音

java - while循环只在deleteMax()堆方法中执行一次

java - 内存游戏 - 将图像数组输入网格按钮矩阵

java - 使用 While 循环从字符串末尾删除逗号

linux - 如何退出一个 while 循环,该循环使用数字和一个不会弄乱数学的字符

java - 如何最好地检测某些异常?

java - 如何比较2个Maps Java的值

Java CDI。拦截器仅在类中的第一个方法调用中被调用

java - 如何使用 NetBeans 为 Java Web 应用程序生成 sun-web.xml?