【问题标题】:Hashmap code not passing all the test casesHashmap 代码未通过所有测试用例
【发布时间】:2021-09-25 12:21:23
【问题描述】:

我试图解决 Java Hashmaps 的问题,我们需要在其中搜索 key 是否存在。如果是,则打印字符串值,否则打印-1。

public static void main(String args[] ) throws Exception {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT */
        Map<Integer,String> hmap=new HashMap<Integer,String>();
        Scanner in=new Scanner(System.in);
        int length= in.nextInt();
        
        for(int i=0;i<length;i++) {
            hmap.put(in.nextInt(),in.nextLine());
        }
        while(in.hasNext()) {
            int number= in.nextInt();
            if(hmap.containsKey(number)) {
                String value=hmap.get(number);
                System.out.println(value);
            }
            else {
                System.out.println(-1);
            }
        }
        in.close();
    }

但是所有的测试用例都没有通过。任何人都可以帮忙解决什么问题吗?

【问题讨论】:

  • 对于什么输入不起作用?

标签: java arrays collections hashmap maps


【解决方案1】:

如果您在 in.nextInt() 之后使用 in.nextLine(),则扫描仪在解释您的输入时会出现问题。这是因为 int 输入的换行符 (\n)(例如 4 ENTER => 4\n)在通过 in.nextInt() 返回 int 后仍然存在,并被 in.nextLine() 识别。 作为解决方法,您可以使用额外的 in.nextLine()。

    for(int i=0;i<length;i++) {
        Integer key =in.nextInt();
        in.nextLine();
        String line = in.nextLine ();
        hmap.put(key,line);
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-24
    • 2022-06-14
    • 2021-12-11
    相关资源
    最近更新 更多