-3

I need to make some kind of phone book using HashMap.

  • If I enter a number the program must ask to enter corresponding name and save that as key and value
  • If I type name, then I must enter the number as well.

number is a key, name is a value.

else if (isPhone(input)) {
    if (phoneBook.containsKey(input)) {
        System.out.println("This number reserve by => " + phoneBook.get(input));
    } else {
        System.out.println("Enter number's owner: " + input);
        String name = scanner.nextLine();
        if (isName(name)) {
            System.out.println("Accept!");
            phoneBook.put(input, name);

Well, it saves the key, but didn't save the value.
enter image description here

Link to full code at GitHub

Tom
  • 16,842
  • 17
  • 45
  • 54
Fa11en
  • 3
  • 1
  • Please add an [MCVE] – Jens Nov 06 '19 at 14:27
  • Hi and welcome to Stack Overflow! Please remember that this is not a free code writing service and you are required to show us what you've tried so far. Please [edit](https://stackoverflow.com/posts/58732297/edit) your post to add a [mre], a [Short, Self Contained, Correct Example](http://www.sscce.org) or at least show us what you've tried so far. Additionally, please read [How to ask](https://stackoverflow.com/help/how-to-ask), a guide on asking questions on Stack Overflow efficiently so that other users may help you faster and better. – yur Nov 06 '19 at 14:28
  • Please consider that it's not good practice on Stack Overflow to externally link to code. You should post all relevant code in your question. Since you're new here, please read the links I provided and then [edit](https://stackoverflow.com/posts/58732297/edit) your question accordingly. Thank you. – yur Nov 06 '19 at 14:29
  • Your code is VERY hard to read. It's full of if/else statements. Probably you should first somehow simplify that code. It's quite normal to have bugs in code that looks like that. – ieggel Nov 06 '19 at 14:41

2 Answers2

1

Like you said yourself: number is key, name is value. But you are trying to give a name as parameter to the get method here:

if (phoneBook.containsValue(input)){
    System.out.println("This person own number => " + phoneBook.get(input));
}

An efficient way of storing and retrieving numbers and names would be to have two HashMaps. One has phone numbers as keys, the other has names as keys.

radulfr
  • 616
  • 3
  • 6
0

Line 44 in your code System.out.println("This person own number => " + phoneBook.get(input)); is wrong.

This will try to get a map entry by the value and this is null.

For Java 8 use Set set = phoneBook.entrySet().stream().filter(entry -> Objects.equals(entry.getValue(), input)).map(Map.Entry::getKey).collect(Collectors.toSet()); System.out.println("This person own number => " + set.toArray()[0]); for example.

Other options can be found here.

ma501
  • 155
  • 7