Why is Scanner.nextLine not running the second and third times?

28 Views Asked by At

I have a program that is supposed to give a user three chances to get a password before it locks them out, but the code is only correctly getting the password on the first attempt.

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        boolean success = false;
        for(int i = 0; i < 3; i++){
            String passInput;
            int numInput;
            System.out.print("Enter password: ");
            passInput = sc.nextLine(); //This line seems to only run on the first iteration of the loop
            //System.out.println(passInput);
            if(passInput.equals("quit")){
                System.out.println("Access denied.");
                success = true; //so that it doesn't print at the bottom
                break;
            }
            System.out.println(passInput);
            System.out.print("Enter number: ");
            numInput = sc.nextInt();
            if(passInput.equals("bluedevils") && numInput == 2023){
                System.out.println("Access granted.");
                success = true;
                break;
            }else{
                System.out.println("Wrong credentials.");
            }
        }
        if(!success){
            System.out.println("Access denied.");
        }
    }
}

I honestly have no clue what to try in order to fix this. It makes absolutely no sense to me that it would work on the first attempt and not on any subsequent ones.

0

There are 0 best solutions below