0

I have recently made a password lock thing in java to test my skills in learning hash maps. This is my code:

package com.Zach.Password;

import java.util.HashMap;
import java.util.Random;
import java.util.Scanner;

public class Password 
{
public static void main(String[] args)
{
    @SuppressWarnings("resource")
    Scanner in = new Scanner(System.in);
    Random r = new Random();
    HashMap<String, String> names = new HashMap<String, String>();
    HashMap<String, Integer> passwords = new HashMap<String, Integer>();
    HashMap<String, Integer> randNums = new HashMap<String, Integer>();

    while(true)
    {
        System.out.println("Please enter your name!!");
        String name = in.nextLine();
        if(names.containsKey(name))
        {
            int tries = 2;
            while(tries != 0)
            {
                if(tries != 0)
                {
                    System.out.println("What is your password?");
                    int normPassword = in.nextInt();

                    if(normPassword == passwords.get(name))
                    {
                        System.out.println("Welcome, " + name);
                        System.out.println("This is your random number:\n");
                        break;
                    }
                    else
                        System.out.println("INCORRECT");
                }
                else if(tries == 0)
                {
                    System.out.println("This account is locked! Unlock it by entering your random number!!");
                    int lockedRand = in.nextInt();
                    if(lockedRand == randNums.get(name))
                    {
                        System.out.println("Welcome, " + name);
                        System.out.println("This is your random number:\n");
                        break;
                    }
                    else
                        System.out.println("INCORRECT");
                }
            }
        }
        else
        {
            int randNum = 1 + r.nextInt(99);
            randNums.put(name, randNum);
            names.put(name, name);
            System.out.println("Enter a password!!");
            int password = in.nextInt();
            passwords.put(name, password);
            System.out.println("Welcome, " + name);
            System.out.println("This is your random number:\n" + randNum);
        }
    }
}

}

I am not sure what the problem is, but whenever you enter a name it goes to the else statement for if names contains key... I do not stop the program and rerun... it just doesn't go down there.

Zach
  • 19
  • 3

1 Answers1

0

You have to use replace in.nextLine() with in.next(); for scanning the name. The in.next(); blocks your application until the user input is submitted. The in.nextLine() gives you just the rest of the current line and changes the position. Therefore it returns only the empty string if no input is given by the user.

Salom
  • 16