Hi I am creating a mock atm, and I created a method to check if the user’s pin is inputted wrong, but if it is wrong it spams incorrect pin 3 times then my program stops, I am looking at how to have the user input incorrectly have it tell them it is wrong once then have them retry their pin until they reach the max 3 attempts.
My while loop is with my ATM class (First time posting bare with me)
MAIN
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); } }
ATM 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; } }
Advertisement
Answer
I don’t see any user input in your code (i.e no Scanner to take in user input), so what’s happening is userPin stays the same throughout each loop.
[userPin is false –> count++ –> print “Incorrect pin”] repeats 3 times, that’s why it spams 3 times.
Here’s the code I’ve rewritten:
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; }