How do I add a limited amount of 3 tries to my loop?

I am trying to limit the maximum login attempts to 3. However, my code below uses all the attempts How would I fix this?

import java.util.Scanner;
import java.util.*;

public class Final {

  public static void main(String[] args) {

    String Username;
    String Password;

    Password = "bruh"; //username and password for the code
    Username = "bro";

    int totalAttempts = 3; //attempt counter
    
    Scanner input1 = new Scanner(System.in);//scanner clasees
    System.out.println("Enter Username : ");
    String username = input1.next();

    Scanner input2 = new Scanner(System.in);
    System.out.println("Enter Password : ");
    String password = input2.next();
    
    //loop also using While statement that i learned from ap classroom
       
    if (username.equals(Username) && password.equals(Password)) {
        System.out.println("Welcome!Username and Password have been validated");
        return;
    } else {
        System.out.println("Username or password invalid");
        totalAttempts--;
    }
 
    if (totalAttempts == 0) {
        System.out.println("Maximum number of attempts exceeded");
    }
  }
}

Answer

Scanner input = new Scanner(System.in);
int attemptsLeft = 3;
while (attemptsLeft > 0) {
    System.out.println("Enter Username:");
    String username = input.nextLine();
    System.out.println("Enter password: ");
    String password = input.nextLine();
    if (username.equals(Username) && password.equals(Password)) {
        System.out.println("Logged in successfully");
        break;
    } else {
        System.out.println("Invalid username or password");
        attemptsLeft--;
    }
}
if (attemptsLeft == 0) {
    System.out.println("You ran out of tries");
}

This code pretty much just uses a while loop to repeat the procedure if the credentials are wrong. If the username and password are right, then the line “break” stops the while loop and you can then proceed with your normal functions. Outside the while loop, it checks to make sure that the attemptsLeft are not 0. If they are, it says “You ran out of tries”.

Leave a Reply

Your email address will not be published. Required fields are marked *