检查用户输入时检查哈希映射中的键

时间:2017-11-11 17:09:50

标签: java

我试图将hashmap的键值与用户输入进行比较,但我不确定应该采取什么方法。

这是我目前的代码:

EXEC sp_executesql

我遇到的问题是,当我尝试使用这个程序时,它总是默认使用else子句,这是因为我习惯使用.equals将它与String值进行比较,但我知道这个是不同的!有谁知道这个解决方案? 好的,所以我找到了一个解决方案... 它有效,但它足够好吗?

Scanner scan = new Scanner(System.in);
    System.out.println("Type an instruction from the list \n 1. hello \n 2. goodbye");
    String input = scan.nextLine();

    HashMap helloMap = new HashMap<>();
    helloMap.put("hello", "you typed hello");

    HashMap goodbyeMap = new HashMap<>();
    goodbyeMap.put("goodbe", "you typed goodbye");


    if(input.equals(helloMap)){

        String helloOutput = (String) helloMap.get("hello");
        System.out.println(helloOutput);

    }
    else if (input.equals(goodbyeMap)){
        String goodbyeOutput = (String) goodbyeMap.get("goodbye");
        System.out.println(goodbyeOutput);

    }
    else{
        System.out.println("Invalid input");
    }

2 个答案:

答案 0 :(得分:0)

问题

您正在将输入StringHashMap对象进行比较。 String对象不等于HashMap对象,这就是布尔表达式始终为false的原因。

解决方案

请查看以下示例:

Map<String, String> outputMap = new HashMap<>();
outputMap.put("hello", "you typed hello");
outputMap.put("goodbye", "you typed goodbye");

System.out.println("Type an instruction from the list \n 1. hello \n 2. goodbye");
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
scan.close();

String output = outputMap.get(input);
if (output == null) {
    System.out.println("Invalid input");
} else {
    System.out.println(output);
}

击穿

  1. 我们定义了一个Map<String, String>,其中包含映射到预定义用户输入的程序响应。
  2. 我们要求用户输入。完成Scanner后,最好通过调用.close()关闭它。
  3. 我们根据用户输入从地图中检索响应。
  4. 我们检查null:如果是null,则表示用户输入不是outputMap的有效密钥。
  5. 打印结果。

答案 1 :(得分:-1)

是的,您需要与地图的实际元素进行比较,而不是地图本身:

Scanner scan = new Scanner(System.in);
    System.out.println("Type an instruction from the list \n 1. hello \n 2. goodbye");
    String input = scan.nextLine();

    HashMap helloMap = new HashMap<>();
    helloMap.put("hello", "you typed hello");

    HashMap goodbyeMap = new HashMap<>();
    goodbyeMap.put("goodbe", "you typed goodbye");


    if(input.equals(helloMap.get("hello"))){

        String helloOutput = (String) helloMap.get("hello");
        System.out.println(helloOutput);

    }
    else if (input.equals(goodbyeMap.get("goodbe"))){
        String goodbyeOutput = (String) goodbyeMap.get("goodbye");
        System.out.println(goodbyeOutput);

    }
    else{
        System.out.println("Invalid input");
    }