224k views
3 votes
Write a simple phonebook program that reads in a series of name-number pairs from the user (that is, name and number on one line separated by whitespace) and stores them in a Map from Strings to Integers. Then ask the user for a name and return the matching number, or tell the user that the name wasn’t found.

User Sagar Pudi
by
6.1k points

1 Answer

3 votes

Answer:

import java.util.HashMap;

import java.util.Map;

import java.util.Scanner;

public class PhoneBook {

public static void main(String[] args) {

Scanner in = new Scanner(System.in);

Map<String, String> map = new HashMap<>();

String name, number, choice;

do {

System.out.print("Enter name: ");

name = in.next();

System.out.print("Enter number: ");

number = in.next();

map.put(name, number);

System.out.print("Do you want to try again(y or n): ");

choice = in.next();

} while (!choice.equalsIgnoreCase("n"));

System.out.print("Enter name to search for: ");

name = in.next();

if (map.containsKey(name)) {

System.out.println(map.get(name));

} else {

System.out.println(name + " is not in the phone book");

}

}

}

User Satish Kilari
by
5.6k points