首页 > 解决方案 > 如何存储 2 个值

问题描述

我必须完成这段代码。我必须找到一种方法来存储 2 个值并使用它们。该程序计算每个候选人的票数,得票最多的候选人为获胜者。哪个工具可以让我做到这一点?

public class vote {

    public vote(String[] candidates) {

    }

    public void votefor(String candidate) {

    }

    public int getnb(String candidate) {

    }

    public String winner() {

    }
  
    public static void main(String[] args) {
        String [] election = {"candidate1", "candidate2"};
        vote v = new vote(election);
        v.votefor("candidate1");
        v.votefor("candidate2");
        v.votefor("candidate1");
        System.out.println("the winner is "+ v.winner());
    }
}

标签: java

解决方案


我建议您使用 aHashMap<String, Integer>来存储对candidate/nbVotes

  • 在初始化时,将每个候选人的分数设为 0
  • votefor候选者加 1时
  • 获得最高分的获胜者
class Vote {

    private HashMap<String, Integer> votes;

    public Vote(String[] candidates) {
        votes = new HashMap<>();
        for (String candidate : candidates) {
            votes.put(candidate, 0);
        }
    }

    public void votefor(String candidate) {
        votes.merge(candidate, 1, Integer::sum);
    }

    public int getnb(String candidate) {
        return votes.get(candidate);
    }

    public String winner() {
        return votes.entrySet().stream().max(Entry.comparingByValue()).map(Entry::getKey).orElse(null);
    }

    public static void main(String[] args) {
        String[] election = {"candidate1", "candidate2"};
        Vote v = new Vote(election);
        v.votefor("candidate1");
        v.votefor("candidate2");
        v.votefor("candidate1");
        System.out.println(v.votes); // {candidate2=1, candidate1=2}
        System.out.println("the winner is " + v.winner()); // the winner is candidate1
    }
}

推荐阅读