首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >哈希映射密码锁java

哈希映射密码锁java
EN

Stack Overflow用户
提问于 2015-08-30 18:44:09
回答 1查看 103关注 0票数 0

最近,我用java做了一个密码锁定项目,以测试我在学习散列映射方面的技能。这是我的密码:

代码语言:javascript
复制
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);
        }
    }
}

}

我不知道问题出在哪里,但是每当您输入一个名称时,它就会转到the语句,因为如果名称包含键.我不会停止程序重新运行..。只是不往下走。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-08-30 19:03:07

您必须使用in.nextLine()替换为in.next();来扫描名称。在提交用户输入之前,in.next();将阻止应用程序。in.nextLine()只提供当前行的其余部分,并更改位置。因此,如果用户没有输入,它只返回空字符串。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32299924

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档