Search code examples
c#loopsone-time-password

Regarding the repetion of block for limited times


I had implemented a random function to generate random OTPs and I wanted the user to enter the incorrect OTP for at most 3times. If the user fails to enter the correct OTP for the fourth consecutive attempt the loop must be terminated. I am unable to sort it out

I've tried this in visual studio and facing this issue of a continuous loop.

string otps = otp.getOtp(); // Get Random otp from getotp method below
Console.WriteLine("OTP Generated:{0}", otps);
do
{
    Console.WriteLine("Enter OTP");
    string userotp = Console.ReadLine(); // Read OTP
    if (userotp == otps) // If OTP is valid
    {
        val1 = false;
        return totalprice;
    }
    else
    {
        while (i >= 1)
        {
            Console.WriteLine("Incorrect OTP");                                          
            Console.WriteLine("Please Re Enter your Password {0} attempts left", i);
            if(userotp != otps)
            {
                val1 = true;
                i--;
            }                                            
            else if (userotp == otps) // If OTP is valid
            {
                val1 = false;
                return totalprice;
            }
        }
     }
 } while (val1);

**************************************  WELCOME TO WALMART  ************************************************
Enter Product Name:
sgf
Enter Product Price:
4356
-----------------------------
 Total price :4356
 -----------------------------
Please Enter Payment option:
 1.CreditCard
 2.NetBanking
 3.Paytm
1
Enter Credit Card Number:
23456789
ReEnter Credit Card Number:
23456789
Enter your Name
Chakradhar
Please Enter CVV Number
***OTP Generated:444
Enter OTP
555
Incorrect OTP
Please Re Enter your Password 3 attempts left
//I NEED TO CALL THE ENTER OTP HERE//
Incorrect OTP
Please Re-Enter your Password 2 attempts left
Incorrect OTP
Please Re-Enter your Password 1 attempts left
Enter OTP

THE ERROR WAS CLEARLY SHOWN IN THE PICTURE BELOW


Solution

  • One thing to note is that setting val1 to terminate the loop and returning doesn't make sense. You are overcomplicating this simple problem. I would suggest a simpler approach:

    string otp=otp.getOtp();
    string input;
    int attemptsLeft=3;
    
    while(attemptsLeft>0)
    {
       Console.WriteLine("Enter OTP");
       input=Console.ReadLine();
       if(input==otp)
           return totalprice;
       else
       {
            Console.WriteLine("Incorrect OTP");  
            Console.WriteLine("Please Re Enter your Password {0} attempts left", attemptsLeft--);
       }
    
    }
    //Handle three unsuccessful attempts