Java程序辅导

C C++ Java Python Processing编程在线培训 程序编写 软件开发 视频讲解

客服在线QQ:2653320439 微信:ittutor Email:itutor@qq.com
wx: cjtutor
QQ: 2653320439

This week’s tutorial is taken from the textbook, exercises 5.25 – 32 on page 174-175. They are reproduced below.

The task is to implement a simple phone book where numbers are associated with names, both represented as strings. Your phone book should be able to add a new name/number pair and you should be able to lookup a number, given a name.

    HashMap<String, String> phoneBook= new HashMap<String, String>();

initialises the phone book. The following statements add new entries:

    phoneBook.put("Charles Nguyen", "(02) 9392 4587");    phoneBook.put("Lisa Jones", "(03) 4536 4674");    phoneBook.put("William H. Smith", "(07) 5488 0123");

Next, we look up an entry:

    String number = phoneBook.get("Lisa Jones");    System.out.println(number);

We refer to the name as the key because it is used for the lookup. Given the above, answer the following questions. You will need to use the Java API documentation.

  1. Create a class MapTester in a new project. In it, use a HashMap to implement a phone book. You will have to import java.util.HashMap. In this class, implement two methods:
    public void enterNumber(String name, String number)

    and

    public String lookupNumber(String name)

    The methods should use put and get methods of the HashMap class to implement their functionality.

  2. What happens when you add an entry to a map with a key that already exists in the map?
  3. What happens when you add an entry to a map with two different keys?
  4. How do you check whether a given key is contained in a map? Try it in Java.
  5. What happens when you try to look up a values and the key does not exist in the map?
  6. How do you check how many entries are contained in the map?
  7. How do you print out all keys currently stored in a map?

No Comments so far ↓

There are no comments yet...Kick things off by filling out the form below.

You must to post a comment.