检查散列映射中是否已存在值,并允许用户输入有效值(如果有)

时间:2016-03-23 05:18:39

标签: java dictionary

我创建了一个小片段来说明我的问题。如果我要输入其中一个用户名,则第一次检查能够确定用户已经存在。但第二个输入能够绕过检查。我该怎么做以确保没有人可以绕过它?

public static void main(String[] args) {
    HashMap<String, String> uID = new HashMap<>();
    Scanner scan = new Scanner(System.in);
    String input = null;
    uID.put("James", "25");
    uID.put("Jack", "25");
    uID.put("John", "25");

    System.out.println("Enter your username and age");

    input = scan.nextLine();
    if (uID.containsKey(input)) {

        System.out.println("Username already exist, choose another username.");
        input = scan.nextLine();
        uID.put(input, "25");

    }
}

4 个答案:

答案 0 :(得分:3)

if语句检查单个条件,然后运行代码块中的代码,如果满足该条件。 while语句是其中的下一个级别。它将检查条件 - 在您的情况下,密钥是否在映射中 - 然后在条件为真时运行代码。在运行代码之后,它再次检查条件,并将一遍又一遍地执行它,直到它停止为真。也就是说,它运行该块中的代码,而条件为true- ,而其输入已经在地图中。

使用while loop检查密钥是否无效,并强制用户继续输入值,直到输入有效值。在验证之后,请不要更新地图值:

public static void main(String[] args) {
    Map<String, String> uID = new HashMap<>();
    Scanner scan = new Scanner(System.in);
    String input = null;
    uID.put("James", "25");
    uID.put("Jack", "25");
    uID.put("John", "25");

    System.out.println("Enter your username and age");

    input = scan.nextLine();
    while (uID.containsKey(input)) {

        System.out.println("Username already exist, choose another username.");
        input = scan.nextLine();
    }

    uID.put(input, "25");
}

答案 1 :(得分:0)

或者,您可以使用do-while循环。

do
{
    System.out.println("Enter unique username and age");
    input = scan.nextLine();
}while(uID.containsKey(input));

uID.put(input, "25");

在我们获取用户名之前,我们要求用户名。

答案 2 :(得分:0)

在检查地图并存储到地图之前,您需要拆分用户名和年龄。

public static void main(String[] args) {
            HashMap<String, String> uID = new HashMap<>();
            Scanner scan = new Scanner(System.in);
            String input = null;
            uID.put("James", "25");
            uID.put("Jack", "25");
            uID.put("John", "25");
            //prompt user to input details
            System.out.println("Enter your username and age");           
            input = scan.nextLine();
            //split name and age
            String arr[]=input.split("\\s");
            //check if name is already present in the map
            while (uID.containsKey(arr[0])) {
                //if already present,prompt user to reenter username alone
                System.out.println("Username already exist, choose another username.");
                //store the username to array's 0th index(as age is already present in 1st index)
                arr[0] = scan.nextLine();                
            }
            //if details not present,then store it to the map
            uID.put(arr[0], arr[1]);
            System.out.println("Your details saved..");
            System.out.println("uID="+uID);
        }

答案 3 :(得分:0)

&#34;如果&#34;是单次条件检查并在条件满足时执行其中的语句,这就是为什么在第一次检查后,第二个输入超过它。 你可以更好地使用&#34;而#34;每次都要进行连续的检查过程并执行报表。