简体   繁体   中英

Dictionary in java using hashmap

I am writing a little phone directory just to practice my knowledge about java. The problem is in the code below i want the code to display the name and the number whenever i call the getname method. I am a beginner and i really wish to make this project work.

public class Phone {

    private HashMap<String, Integer> name;
    HashMap<String, Integer> namelist = new HashMap<String, Integer>();
    Integer number;
    String names;

    /**
     * @return the name
     */
    Phone() {

        // get user to enter name and number
        Scanner scan = new Scanner(System.in);
        System.out.println("enter name ");
        names = scan.nextLine();

        System.out.println("enter number ");
        String nums = scan.nextLine();
        number = Integer.parseInt(nums);

        namelist.put(names, number); // set key and value to namelist object;

        setName(namelist); //

    }

    void printValue() {

        System.out.print(namelist.get(names));

    }

    public HashMap<String, Integer> getName() {
        return name;
    }

    /**
     * @param names
     *            the name to set
     */
    public void setName(HashMap<String, Integer> names) {
        this.name = names;
    }

    public static void main(String[] args) {

        Phone ph = new Phone();
        Gui window = new Gui();
        System.out.println(ph.getName());
        ph.printValue();


    }

}

Your getName() method should return a String, not a HashMap; you'll need to concatenate the name and number before returning them, eg return name + "; " + Integer.toString(number);

I assume that by saying "display the name and the number", you want to display all contacts stored in the phone. So the quesiton seems like how to print all elements in a hashmap.

        for(String name : map.keySet()){
        System.out.println("name is " + name);
        System.out.println("contact is " + map.get(name));}

Here is an even easier answer:

System.out.println(map);

This invokes the toString() method on Map which invokes the toString() methods of the key and value and that implementation reports key/value pairings as such:

"joe" -> "123456789"

The only caveat is the default does not place a newline between elements. If you want to do that you can do:

for(Map.Entry<String,Integer> entry: map.Entry())
    system.out.println(entry);

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