Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confused with recursive methods & loops

I wrote the method below, but it doesn't work correctly.

Even if the pin is not correct, this program execute the next method in Main class.

The main idea is just when your pin is correct, than method will finished and the program go to the next method. If PIN isn't correct, than you will have 3 times. If all efforts were wrong, than the program will go out. So, your card will be blocked. Please, give me a peace of advise.

public boolean authenticity(short pin)  {
       if (pin == 1234) {
           System.out.println("PIN is correct");
           System.out.println("Card is active for operation!");
           return true;
       } else {
           pin = sc.nextShort();
           for (int i = 1; i >= 3; i++) {
               System.out.println("PIN isn't correct! You have " +i +"effort(s)");
               return authenticity(pin);  // recursion
           }
       }
       return false;
  }

*In the Main class the method is executed according to the command: authenticity(sc.nextShort());

like image 210
Aleksei Moshkov Avatar asked Feb 10 '23 18:02

Aleksei Moshkov


1 Answers

First of all, the loop's condition should be i > 0 :

       for (int i = 3; i > 0; i--) {
           System.out.println("PIN isn't correct! You have " +i +"effort(s)");
           return authenticity(pin);  
       }

Second of all, in your current implementation, each recursive call will give the user 3 additional attempts (at least until a StackOverflow occurs). You should pass the number of remaining attempts as a parameter to the recursive call. And you don't need a loop.

public boolean authenticity(short pin, int remainingAttempts) {
    if (pin == 1234) {
        System.out.println("PIN is correct");
        System.out.println("Card is active for operation!");
        return true;
    } else {
        pin = sc.nextShort();
        remainingAttempts--;
        if (remainingAttempts > 0) {
            System.out.println("PIN isn't correct! You have " +remainingAttempts +" attempts left");
            return authenticity(pin,remainingAttempts);
        }
    }
    return false;
}

If you wish to keep the loop, you can get rid of the recursion.

like image 109
Eran Avatar answered Feb 12 '23 08:02

Eran