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

Create 20. Phone book 2: Searching for a number

Browse files
Week 3: Objects, files and exceptions/20. Phone book 2: Searching for a number ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ q20
2
+ Write the method
3
+
4
+ void findNumber(HashMap<String,String> numbers)
5
+
6
+ which prompts the user to enter a name and then searches and
7
+ prints a number from the phone book that matches the name.
8
+ If the name is not found, the program prints an error message according to the model response.
9
+
10
+ Example of a method call:
11
+ public static void main(String[] args){
12
+ HashMap<String,String> numbers = new HashMap<>();
13
+ numbers.put("Tim", "12345");
14
+ numbers.put("Kate", "54321");
15
+ numbers.put("Jun", "55555");
16
+
17
+ findNumber(numbers);
18
+ findNumber(numbers);
19
+ findNumber(numbers);
20
+ }
21
+
22
+
23
+
24
+ Example execution:
25
+ Name: Tim
26
+ Number: 12345
27
+ Name: Kate
28
+ Number: 54321
29
+ Name: Patricia
30
+ Name not found
31
+
32
+
33
+
34
+
35
+
36
+
37
+ import java.util.Random;
38
+ import java.util.Arrays;
39
+ import java.util.HashMap;
40
+ import java.util.Collections;
41
+ import java.util.ArrayList;
42
+ import java.util.Scanner;
43
+
44
+
45
+
46
+ public class Test{
47
+ public static void main(String[] args){
48
+ final Random r = new Random();
49
+
50
+ findNumber(numbers);
51
+ }
52
+
53
+
54
+ //q20
55
+ public static void findNumber(HashMap<String,String> numbers) {
56
+ // Let user enter a name
57
+ Scanner reader = new Scanner(System.in);
58
+ System.out.print("Name: ");
59
+ String name = reader.nextLine();
60
+
61
+ // then find the name and their number
62
+ if (numbers.containsKey(name)) {
63
+ System.out.println("Number: " + numbers.get(name));
64
+ }
65
+ else {
66
+ System.out.println("Name not found");
67
+ }
68
+ }
69
+
70
+
71
+
72
+ }
73
+
74
+
75
+
76
+
77
+
78
+
79
+
80
+
81
+ Phone book:
82
+ Kim: 39652
83
+ Lena: 289930
84
+ Pete: 769067
85
+ Testing with input [Pete]
86
+ Name: Pete
87
+ Number: 769067
88
+
89
+ Testing with input [Jane]
90
+ Name: Jane
91
+ Name not found
92
+
93
+ Testing with input [Kim]
94
+ Name: Kim
95
+ Number: 39652
96
+
97
+ Testing with input [Lena]
98
+ Name: Lena
99
+ Number: 289930
100
+
101
+
102
+