public class JavaStudy01 {
public static void main(String[] args) {
List<Integer> randomVoteList = createRandomVoteList(100000, 4);
ArrayList<Candidate> candidates = new ArrayList<>();
candidates.add(new Candidate("이재명"));
candidates.add(new Candidate("윤석열"));
candidates.add(new Candidate("심상정"));
candidates.add(new Candidate("안철수"));
VoteCalculator voteCalculator = new VoteCalculator(candidates);
voteCalculator.calc(randomVoteList);
}
private static List<Integer> createRandomVoteList(int size, int candidates) {
ArrayList<Integer> voteList = new ArrayList<>();
Random random = new Random();
for (int i = 0; i < size; i++) {
voteList.add(random.nextInt(candidates) + 1);
}
return voteList;
}
}
class VoteCalculator {
private final Map<Integer, Candidate> candidates;
public VoteCalculator(List<Candidate> candidates) {
this.candidates = IntStream.range(0, candidates.size())
.boxed()
.collect(Collectors.toMap(voteNum -> voteNum + 1, candidates::get));
}
public void calc(List<Integer> voteList) {
int progress = 0;
int size = voteList.size();
for (Integer vote : voteList) {
progress++;
Candidate candidate = candidates.get(vote);
candidate.addVoted();
String info = String.format("[투표진행율]:%.2f%%, %d명 투표 => %s", progress * 100.0 / size, progress, candidate.getName());
String progressStatus = getProgressStatus(size);
System.out.println(info);
System.out.println(progressStatus);
}
String winner = candidates.values()
.stream().max(Comparator.comparingInt(Candidate::getVoted)).map(Candidate::getName).orElse("");
System.out.println("[투표결과] 당선인: " + winner);
}
private String getProgressStatus(int size) {
StringBuilder stb = new StringBuilder();
candidates.forEach((key, value) -> stb.append(String.format("[기호%d] %s: %.2f%%, (투표수: %d)\n",
key,
value.getName(),
value.getVoted() * 100.0 / size,
value.getVoted())));
return stb.toString();
}
}
class Candidate {
private final String name;
private Integer voted;
public Candidate(String name) {
this.name = name;
this.voted = 0;
}
public String getName() {
return name;
}
public Integer getVoted() {
return voted;
}
public void addVoted() {
voted++;
}
}
JavaStudy06.java
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.