'C# User input Password log in session
I'm trying to create a text-based password log-in for a class project. Unfortunately, it's C#, not python. So I make it so if the user gets it wrong it says incorrect but if they get it correct it says correct.The problem I am having is that I can't loop/retry it when I get it incorrect. Does anyone have suggestions or answers to this? (I have the example code below)
Thanks!
using System;
public class Program
{
public static void Main()
{
int Password = 1234;
Console.WriteLine("Enter the password in order to enter");
Password = Convert.ToInt32(Console.ReadLine());
if (Password == 1234)
{
Console.WriteLine("Processing...");
Console.WriteLine("Access Granted");
}
else
{
Console.WriteLine("Processing...");
Console.WriteLine("Access Denied");
Console.WriteLine("Try again...");
}
}
}
Solution 1:[1]
You can do a While loop and break when the password matches. Something like this:
int correctPassword = 1234;
while (true)
{
Console.Write("Enter the password in order to enter: ");
string? informedPassword = Console.ReadLine();
Console.WriteLine("Processing...");
if (informedPassword == correctPassword.ToString())
{
Console.WriteLine("Access granted!");
break;
}
else
{
Console.WriteLine("Access denied!");
Console.WriteLine("Try again...");
}
Console.WriteLine();
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Irineu Santos |
