简体   繁体   中英

Using Hashmaps with Scanner() function

The following code is my attempt at a hashmap that works as a phonebook. There are names and phone numbers, and if you enter a name that is not in the directory, the code returns "Not found".

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");
            }
        }

    }
}

When I run the program, I get a runtime error: ~ no response on stdout ~

The snippet

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

advances the scanner twice (actually three times). So the key which is checked is not the name, but the part after the phone number. Change to if(hmap.containsKey(name)) , since you already scanned and the name from the input and stored it into the variable. Everytime you call sc.next() the scanner is advanced and it consumes one token of the input. If you want to re-use values, you have to store them in a variable and then reference that variable.

Not sure why your input contains the phone number too, if you only want to lookup by name?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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