File size: 2,173 Bytes
147dc58
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
19-22
building a simple phonebook application one method at a time. 
The phonebook must be able to add, search and list numbers. I
In addition, the application has a simple menu from which you can select the desired functionality.

The data structure is a hash table, where both keys and values are strings.


===========================================

19



Write the method

void addNumber(HashMap<String,String> numbers)

which asks the user to enter a name and a number and 
then adds them to the hash table (so that the name is the key and the number is the value).



An example of a method call:
public static void main(String[] args){
    HashMap<String,String> numbers = new HashMap<>();
    addNumber(numbers);
    System.out.println(numbers);
}


Example execution:
Name: Jack Java
Number: 1234567
{Jack Java=1234567}




 



import java.util.Random;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Collections;
import java.util.ArrayList;
import java.util.Scanner;



public class Test{
    public static void main(String[] args){
        final Random r = new Random();

            addNumber(numbers);
            System.out.println("Book now:");
            
            ArrayList<String> names = new ArrayList<>(numbers.keySet());
            Collections.sort(names);
            for (String name : names) {
                System.out.println(name + ": " + numbers.get(name));
            }  
    }
    

    // q19
    // add name and number to input HashMap directly
    public static void addNumber(HashMap<String,String> numbers) {
        Scanner reader = new Scanner(System.in);

        System.out.print("Name: ");
        String name = reader.nextLine();
        System.out.print("Number: ");
        String number = reader.nextLine();
        
        numbers.put(name, number);
    }


}




Testing with input [Jack, 1234-567]
Name: Jack
Number: 1234-567
Book now:
Jack: 1234-567

Testing with input [Pete, 020-9876543]
Name: Pete
Number: 020-9876543
Book now:
Jack: 1234-567
Pete: 020-9876543

Testing with input [Ann, 123-456543]
Name: Ann
Number: 123-456543
Book now:
Ann: 123-456543
Jack: 1234-567
Pete: 020-9876543