My friendship


Submit solution

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

Authors:
Problem type
Allowed languages
Java 19, Java 8

題目說明

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

import java.util.*;
public class t05163 {

    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("Subject: " + person.get("subject"));
            System.out.println();
        }
    }

}

輸入

先輸入好友人數,接著輸入相對應的信息到hashmap中做存放:

Name (String)
Subject (String)

輸出

所有友人的信息

測試資料 輸入

3 小李 資管系 小陳 英文系 小黑 中文系

測試資料 輸出

Name: 小李
Subject: 資管系

Name: 小陳
Subject: 英文系

Name: 小黑
Subject: 中文系

Comments


  • 0
    scu09156146  commented on May 17, 2024, 1:43 p.m.

    題解

    // 參考課堂範例A271

    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.Scanner;
    
    public class MyFriendship {
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            ArrayList<HashMap<String, String>> friends = new ArrayList<>();
    
            Scanner in = new Scanner(System.in);
            int c = in.nextInt();
            // Create and add HashMap objects to the ArrayList
            HashMap<String, String> person1;
            for (int i = 0; i < c; i++) {
                person1 = new HashMap<>();
                String s1 = in.next();
                String s2 = in.next();
                person1.put("name", s1);
                person1.put("subject", s2);
                friends.add(person1);
            }
    
            // Iterate over the ArrayList and print details of each person
            // Each of them is a HashMap object
            for (HashMap<String, String> person : friends) {
                System.out.println("Name: " + person.get("name"));
                System.out.println("Subject: " + person.get("subject"));
                System.out.println();
            }
            in.close();
        }
    
    }