繁体   English   中英

使用带有 Scanner() 的哈希图 function

[英]Using Hashmaps with Scanner() function

以下代码是我对用作电话簿的 hashmap 的尝试。 有姓名和电话号码,如果输入的姓名不在目录中,则代码返回“未找到”。

import java.util.*;
import java.io.*;
import java.util.HashMap.*;

class Solution{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();

        for(int i = 0; i < n; i++){
            String name = sc.next();
            int phone = sc.nextInt();
            HashMap<Integer, String> hmap = new HashMap<Integer, String>();
        }

        while(sc.hasNext()){
            String name = sc.next();
            int phone = sc.nextInt();
            if(hmap.containsKey(sc.next())){
                System.out.println(name + "=" + phone);
            } else {
                System.out.println("Not found");
            }
        }

    }
}

当我运行程序时,我得到一个运行时错误:~ stdout 上没有响应~

片段

            String name = sc.next();
            int phone = sc.nextInt();
            if(hmap.containsKey(sc.next())){

使扫描仪前进两次(实际上是三次)。 所以检查的关键不是姓名,而是电话号码后面的部分。 更改为if(hmap.containsKey(name)) ,因为您已经扫描了输入中的名称并将其存储到变量中。 每次您调用sc.next()时,扫描仪都是高级的,它会消耗一个输入标记。 如果要重用值,则必须将它们存储在变量中,然后引用该变量。

如果您只想按姓名查找,不确定为什么您的输入也包含电话号码?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM