Ejercicio
Contraseña 5 intentos
Objetivo
Escriba un programa en C# que solicite al usuario su nombre de usuario y contraseña. Ambos deben ser cadenas. Después de 5 intentos erróneos, el usuario será rechazado.
Código de Ejemplo
using System; // Import the System namespace to use basic classes like Console
class Program // Define the main class of the program
{
static void Main() // The entry point of the program
{
string username; // Declare a variable to store the username
string password; // Declare a variable to store the password
int attempts = 0; // Variable to count the number of incorrect attempts
// Allow a maximum of 5 attempts
while (attempts < 5)
{
// Ask the user for their username
Console.Write("Enter your username: ");
username = Console.ReadLine(); // Read the username input from the user
// Ask the user for their password
Console.Write("Enter your password: ");
password = Console.ReadLine(); // Read the password input from the user
// Check if the username and password are correct
if (username == "username" && password == "password") // If both are correct
{
Console.WriteLine("Welcome! You have successfully logged in."); // Display a welcome message
return; // Exit the program successfully
}
else // If the username or password is incorrect
{
attempts++; // Increment the number of attempts
Console.WriteLine("Invalid username or password. Attempts left: " + (5 - attempts)); // Display error message and remaining attempts
}
}
// If the user reaches 5 incorrect attempts, display a rejection message
Console.WriteLine("You have been rejected after 5 incorrect attempts.");
}
}