关于限时重复区块

Regarding the repetion of block for limited times

我实现了一个随机函数来生成随机 OTP,我希望用户最多输入 3 次错误的 OTP。如果用户连续第四次尝试输入正确的 OTP 失败,则必须终止循环。我无法解决

我已经在 visual studio 中尝试过,并且遇到了这个连续循环的问题。

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

需要注意的一点是,设置val1终止循环并返回是没有意义的。你把这个简单的问题复杂化了。我会建议一个更简单的方法:

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