TurkuBasicOOPinJava / Week 3: Objects, files and exceptions /20. Phone book 2: Searching for a number
KaiquanMah's picture
containsKey get
a1db57c verified
raw
history blame
1.77 kB
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