问题
I'm new to this language, I tried things but couldn't figure out how to set a login loop to use login attemps with a max. of 3 times. Could someone help me out?
static void Main(string[] args)
{
Console.WriteLine("Status: " + status.Onaangemeld);
Console.WriteLine("Welkom, typ hieronder het gebruikersnaam:");
string Naam = Console.ReadLine();
Console.WriteLine("Vul hieronder het wachtwoord in:");
string Wachtwoord = Console.ReadLine();
if (Naam == "gebruiker" && Wachtwoord == "SHARPSOUND")
{
Console.Clear();
Console.WriteLine("Status: " + status.Ingelogd);
Console.WriteLine("Welkom bij SoundSharp {0}!", Naam);
Console.ReadLine();
}
else
Console.Clear();
Console.WriteLine("Helaas, gebruikersnaam of wachtwoord niet correct.");
}
}
回答1:
static void Main(string[] args)
{
for (int i=0; i<3; i++)
{
Console.WriteLine("Status: " + status.Onaangemeld);
Console.WriteLine("Welkom, typ hieronder het gebruikersnaam:");
string Naam = Console.ReadLine();
Console.WriteLine("Vul hieronder het wachtwoord in:");
string Wachtwoord = Console.ReadLine();
if (Naam == "gebruiker" && Wachtwoord == "SHARPSOUND")
{
Console.Clear();
Console.WriteLine("Status: " + status.Ingelogd);
Console.WriteLine("Welkom bij SoundSharp {0}!", Naam);
Console.ReadLine();
break;
}
Console.Clear();
Console.WriteLine("Helaas, gebruikersnaam of wachtwoord niet correct.");
}
Console.Clear();
Console.WriteLine("....");
}
}
回答2:
You should add the for loop for maximum number of attempts. For reference you can read below
https://msdn.microsoft.com/en-us/library/ch45axte.aspx
You can use for loop accordingly whether you want the user to enter password only or username and password both
回答3:
Why not recursive
class Program
{
const int MaxAttempt = 3;
static int currentAttempt = 0;
static void Main(string[] args)
{
if (MaxAttempt == currentAttempt)
{
Console.WriteLine("You have reached maximum try .. please come after some time");
Console.ReadLine();
Environment.Exit(0);
}
currentAttempt++;
Console.WriteLine("Status: " + status.Onaangemeld);
Console.WriteLine("Welkom, typ hieronder het gebruikersnaam:");
string Naam = Console.ReadLine();
Console.WriteLine("Vul hieronder het wachtwoord in:");
string Wachtwoord = Console.ReadLine();
if (Naam != "gebruiker" || Wachtwoord != "SHARPSOUND")
{
Console.Clear();
Console.WriteLine("Helaas, gebruikersnaam of wachtwoord niet correct. Please try again");
Console.ReadLine();
Console.Clear();
Main(args);
}
Console.Clear();
Console.WriteLine("Status: " + status.Ingelogd);
Console.WriteLine("Welkom bij SoundSharp {0}!", Naam);
Console.ReadLine();
}
}
来源:https://stackoverflow.com/questions/36399538/how-to-add-c-sharp-login-attempts-loop-in-console-application