如何在我的方法中正确使用此 while 循环让用户重试输入最多 3 次

How to properly use this while loop within my method to have user retry input to a maximum of three times

你好,我正在创建一个模拟 atm,我创建了一个方法来检查用户的密码是否输入错误,但如果输入错误,它会向错误的密码发送 3 次垃圾邮件,然后我的程序停止,我正在研究如何让用户输入不正确让它告诉他们这是错误的一次然后让他们重试他们的 pin 直到他们达到最多 3 次尝试。

我的 while 循环在我的 ATM 上 class(我第一次裸发)

主要

import java.util.Scanner;

public class Main {
    public static void main(String[] args){
        Scanner enterPin = new Scanner(System.in);
        System.out.println("Enter your 4 digit pin: ");
        String userPin = enterPin.nextLine();
        ATM pin = new ATM("1234");
        pin.checkPin(userPin);
    }
}

A​​TM CLASS


public class ATM {
    String pin;
    int counter;
    public ATM(String pin){ //constructor 1 for pin
        this.pin = pin;
    }
    public ATM(int counter){ //constructor for counting how many times pin is entered
        this.counter = counter;
    }
    public String getPin(){
        return pin;
    }
    public boolean setPin(String pin){
        this.pin = pin;
        return true;
    }
    public boolean checkPin(String userPin){
        while(!userPin.contains(pin) && counter < 3) {
                System.out.println("Incorrect pin.");
                counter += 1;
            if (counter >= 3){
                System.out.println("Incorrect pin your account has been blocked.");
                return false;
            }
        }
        if(userPin.contains(pin)){
            System.out.println("Your pin is correct!");
        }
        return true;
    }

}

我在你的代码中没有看到任何用户输入(即没有扫描器接收用户输入),所以发生的事情是 userPin 在每个循环中保持不变。

[userPin is false --> count++ --> print "Incorrect pin"] 重复 3 次,这就是它发送 3 次垃圾邮件的原因。

这是我重写的代码:

public boolean checkPin() {
    int counter = 0;
    Scanner scanner = new Scanner(System.in);
    while(counter < 3) {
        String userPin = scanner.nextLine();
        if(userPin.contains(pin)){
            System.out.println("Your pin is correct!");
            return true;
        }
        System.out.println("Incorrect pin.");
        counter += 1;
    }
    System.out.println("Too many tries, your account has been blocked.");
    return false;
}