KaiquanMah commited on
Commit
147dc58
·
verified ·
1 Parent(s): f7e663a

public static void addNumber(HashMap<String,String> numbers)

Browse files
Week 3: Objects, files and exceptions/19. Phone book 1: Adding a number ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 19-22
2
+ building a simple phonebook application one method at a time.
3
+ The phonebook must be able to add, search and list numbers. I
4
+ In addition, the application has a simple menu from which you can select the desired functionality.
5
+
6
+ The data structure is a hash table, where both keys and values are strings.
7
+
8
+
9
+ ===========================================
10
+
11
+ 19
12
+
13
+
14
+
15
+ Write the method
16
+
17
+ void addNumber(HashMap<String,String> numbers)
18
+
19
+ which asks the user to enter a name and a number and
20
+ then adds them to the hash table (so that the name is the key and the number is the value).
21
+
22
+
23
+
24
+ An example of a method call:
25
+ public static void main(String[] args){
26
+ HashMap<String,String> numbers = new HashMap<>();
27
+ addNumber(numbers);
28
+ System.out.println(numbers);
29
+ }
30
+
31
+
32
+ Example execution:
33
+ Name: Jack Java
34
+ Number: 1234567
35
+ {Jack Java=1234567}
36
+
37
+
38
+
39
+
40
+
41
+
42
+
43
+
44
+ import java.util.Random;
45
+ import java.util.Arrays;
46
+ import java.util.HashMap;
47
+ import java.util.Collections;
48
+ import java.util.ArrayList;
49
+ import java.util.Scanner;
50
+
51
+
52
+
53
+ public class Test{
54
+ public static void main(String[] args){
55
+ final Random r = new Random();
56
+
57
+ addNumber(numbers);
58
+ System.out.println("Book now:");
59
+
60
+ ArrayList<String> names = new ArrayList<>(numbers.keySet());
61
+ Collections.sort(names);
62
+ for (String name : names) {
63
+ System.out.println(name + ": " + numbers.get(name));
64
+ }
65
+ }
66
+
67
+
68
+ // q19
69
+ // add name and number to input HashMap directly
70
+ public static void addNumber(HashMap<String,String> numbers) {
71
+ Scanner reader = new Scanner(System.in);
72
+
73
+ System.out.print("Name: ");
74
+ String name = reader.nextLine();
75
+ System.out.print("Number: ");
76
+ String number = reader.nextLine();
77
+
78
+ numbers.put(name, number);
79
+ }
80
+
81
+
82
+ }
83
+
84
+
85
+
86
+
87
+ Testing with input [Jack, 1234-567]
88
+ Name: Jack
89
+ Number: 1234-567
90
+ Book now:
91
+ Jack: 1234-567
92
+
93
+ Testing with input [Pete, 020-9876543]
94
+ Name: Pete
95
+ Number: 020-9876543
96
+ Book now:
97
+ Jack: 1234-567
98
+ Pete: 020-9876543
99
+
100
+ Testing with input [Ann, 123-456543]
101
+ Name: Ann
102
+ Number: 123-456543
103
+ Book now:
104
+ Ann: 123-456543
105
+ Jack: 1234-567
106
+ Pete: 020-9876543
107
+
108
+
109
+
110
+