Exercise
Password V2
Objetive
Write a java program to ask the user for their login and password (both must be integer numbers) until the entered login is "12" and the password is "1234". The user will have a maximum of three attempts.
Example Code
// Importing the Scanner class to handle input from the user
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Declare variables for login, password, and attempt counter
int login;
int password;
int attempts = 0;
// Create a Scanner object to read user input
Scanner scanner = new Scanner(System.in);
// Loop to allow a maximum of 3 attempts
while (attempts < 3) {
// Ask the user for the login
System.out.print("Enter login: ");
login = scanner.nextInt();
// Ask the user for the password
System.out.print("Enter password: ");
password = scanner.nextInt();
// Check if login and password are correct
if (login == 12 && password == 1234) {
System.out.println("Access granted.");
return; // Exit the program if the credentials are correct
} else {
// Increment the number of attempts
attempts++;
// Display a message if the login or password is incorrect
System.out.println("Invalid login or password. Try again.");
}
}
// Inform the user if they failed to login after 3 attempts
System.out.println("Maximum attempts reached. Access denied.");
}
}