TurkuBasicOOPinJava / Week 3: Objects, files and exceptions /19. Phone book 1: Adding a number
KaiquanMah's picture
public static void addNumber(HashMap<String,String> numbers)
147dc58 verified
raw
history blame
2.17 kB
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