(OJ)Java容器-Map的使用

Map的使用

Problem Description

1.实验目的
(1) 掌握Map的创建及遍历

2.实验容
  编写Account类,含账户id(Integer型)、余额balance(Double型)属性及相应get、set方法,接着完成类Helper的input方法完成账户输入(注意输入串要含有账户id及余额两类信息)进Account对象,并存储进Map(此处用linkedHashMap保证输入顺序在输出时不变)中,接着遍历Map并给出信息提示。

3.实验要求:
  请完成Account类、Helper类
  import java.util.*;
     public class Main { 
         public static void main(String[] args) {
              Map<Integer,Account> mp  =new linkedHashMap<>();
              Helper helper = new Helper();
              // 输入数据进Map
              helper.inputMap(mp);
              // 遍历Map
              helper.visitMap(mp);
         }
    }
    // 你的代码

Input Description

12,450;67,780;56,1000

Output Description

id=12, balance=450.0
id=67, balance=780.0
id=56, balance=1000.0

解题代码

// 账户 Account类
class Account{
    
    
    // 账户id
    private Integer id;

    // 余额 balance 
    private Double balance;

    // 带参构造
    public Account(Integer id, Double balance) {
    
    
        this.id = id;
        this.balance = balance;
    }

    // 无参构造
    public Account() {
    
    
    }

    // get set
    public Integer getId() {
    
    
        return id;
    }

    public void setId(Integer id) {
    
    
        this.id = id;
    }

    public Double getBalance() {
    
    
        return balance;
    }

    public void setBalance(Double balance) {
    
    
        this.balance = balance;
    }

    // toString方法
    @Override
    public String toString() {
    
    
        return "id=" + id + ", balance=" + balance;
    }
}

// Helper类
class Helper{
    
    

    // inputMap方法 接收输入的账户数据 存入传递的Map集合中
    public void  inputMap(Map map){
    
    
        Scanner in = new Scanner(System.in);
        String line = in.nextLine();
        String[] strs = line.split(";");
        for(String s:strs){
    
    
            String[] infos = s.split(",");
            Account account = new Account(Integer.parseInt(infos[0]), Double.parseDouble(infos[1]));
            map.put(account.getId(),account);
        }
        in.close();
    }

    // 显示所有的账户信息
    public void  visitMap(Map map){
    
    
        Set keys = map.keySet();
        for (Object key: keys){
    
    
            System.out.println(map.get(key));
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_40856560/article/details/112604141