Contact Info


Submit solution

Points: 60 (partial)
Time limit: 1.0s
Memory limit: 256M

Authors:
Problem types
Allowed languages
Java 19, Java 8

題目說明

請設計一類似電話簿的程式,讓使用者可以輸入聯絡人的信息並記錄下來,最後輸出電話簿中所有聯絡人的信息

import java.util.*;
public class ContactInfo {

    public static void main(String[] args) {
        ArrayList<HashMap<String, String>> friends = new ArrayList<>();

        /*
            補上缺少的程式碼
        */

        // 印出聯絡人信息
        for (HashMap<String, String> person : friends) {
            System.out.println("Name: " + person.get("Name"));
            System.out.println("Office: " + person.get("Office"));
            System.out.println("Ext: " + person.get("Ext"));
            System.out.println();
        }
    }

}

輸入

先輸入有幾位聯絡人,接著輸入相對應的信息到HashMap中做存放:

Name    (String)    名字
Office  (String)    辦公室
Ext     (String)    分機號碼

輸出

所有聯絡人的信息

測試資料 輸入

3
JJ 4204 2800
KK 4219 3807
LL 3205 3801

測試資料 輸出

Name: JJ
Office: 4204
Ext: 2800

Name: KK
Office: 4219
Ext: 3807

Name: LL
Office: 3205
Ext: 3801

Comments


  • 0
    scu09156146  commented on May 21, 2024, 2:13 p.m.

    題解

    // 參考DMOJ小考題

    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.Scanner;
    
    public class ContactInfo {
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            ArrayList<HashMap<String, String>> contactBook = new ArrayList<>(); // 電話簿
            HashMap<String, String> person; // 用來暫存個人資訊的欄位名稱(key)、資料(value)
    
            Scanner in = new Scanner(System.in);
            int n = in.nextInt();
            for (int i = 0; i < n; i++) {
                // 用new的方式,創建新的(空的)HashMap
                person = new HashMap<>();
                // 先在HashMap暫存
                person.put("Name", in.next());
                person.put("Office", in.next());
                person.put("Ext", in.next());
                // 所有欄位紀錄完,再登錄到電話簿(ArrayList)
                contactBook.add(person);
            }
            in.close();
    
            // Iterate over the ArrayList and print details of each person
            // Each of them is a HashMap object
            for (HashMap<String, String> person1 : contactBook) {
                System.out.println("Name: " + person1.get("Name"));
                System.out.println("Office: " + person1.get("Office"));
                System.out.println("Ext: " + person1.get("Ext"));
                System.out.println();
            }
        }
    
    }