Spaces:
Running
Running
File size: 1,773 Bytes
06dc87c a1db57c | 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 | q20
Write the method
void findNumber(HashMap<String,String> numbers)
which prompts the user to enter a name and then searches and
prints a number from the phone book that matches the name.
If the name is not found, the program prints an error message according to the model response.
Example of a method call:
public static void main(String[] args){
HashMap<String,String> numbers = new HashMap<>();
numbers.put("Tim", "12345");
numbers.put("Kate", "54321");
numbers.put("Jun", "55555");
findNumber(numbers);
findNumber(numbers);
findNumber(numbers);
}
Example execution:
Name: Tim
Number: 12345
Name: Kate
Number: 54321
Name: Patricia
Name not found
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();
findNumber(numbers);
}
//q20
public static void findNumber(HashMap<String,String> numbers) {
// Let user enter a name
Scanner reader = new Scanner(System.in);
System.out.print("Name: ");
String name = reader.nextLine();
// then find the name and their number
if (numbers.containsKey(name)) {
System.out.println("Number: " + numbers.get(name));
}
else {
System.out.println("Name not found");
}
}
}
Phone book:
Kim: 39652
Lena: 289930
Pete: 769067
Testing with input [Pete]
Name: Pete
Number: 769067
Testing with input [Jane]
Name: Jane
Name not found
Testing with input [Kim]
Name: Kim
Number: 39652
Testing with input [Lena]
Name: Lena
Number: 289930
|