Grupo
Tipos de datos básicos de C#
Objectivo
Escriba un programa en C# que solicite al usuario su nombre de usuario y contraseña. Ambos deben ser cadenas. Tras 5 intentos incorrectos, el usuario será rechazado.
Ejemplo de ejercicio en C#
Mostrar código C#
using System;
class Program
{
static void Main()
{
// Correct credentials
string correctUsername = "username";
string correctPassword = "password";
int maxAttempts = 5; // Maximum number of allowed attempts
int attemptCount = 0; // Counter for attempts
string enteredUsername, enteredPassword;
while (attemptCount < maxAttempts)
{
// Prompt the user for username
Console.Write("Enter your username: ");
enteredUsername = Console.ReadLine();
// Prompt the user for password
Console.Write("Enter your password: ");
enteredPassword = Console.ReadLine();
// Check if the credentials match
if (enteredUsername == correctUsername && enteredPassword == correctPassword)
{
Console.WriteLine("\nAccess granted. Welcome!");
return; // Exit the program
}
else
{
attemptCount++;
Console.WriteLine($"Incorrect username or password. Attempts left: {maxAttempts - attemptCount}\n");
}
}
// If max attempts are reached
Console.WriteLine("Too many failed attempts. Access denied.");
}
}
Output
//Example 1 (Incorrect Attempts Followed by Success):
Enter your username: admin
Enter your password: 1234
Incorrect username or password. Attempts left: 4
Enter your username: user
Enter your password: pass
Incorrect username or password. Attempts left: 3
Enter your username: username
Enter your password: password
Access granted. Welcome!
//Example 2 (Exceeding Maximum Attempts):
Enter your username: admin
Enter your password: 1234
Incorrect username or password. Attempts left: 4
Enter your username: user
Enter your password: pass
Incorrect username or password. Attempts left: 3
Enter your username: guest
Enter your password: 0000
Incorrect username or password. Attempts left: 2
Enter your username: test
Enter your password: abc
Incorrect username or password. Attempts left: 1
Enter your username: hacker
Enter your password: qwerty
Incorrect username or password. Attempts left: 0
Too many failed attempts. Access denied.
Código de ejemplo copiado
Comparte este ejercicio de C#