Last active
January 15, 2024 08:02
-
-
Save Starlight258/f61524add37f70d1479f496008f086d0 to your computer and use it in GitHub Desktop.
0114_과제6
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 김명지 | |
import java.util.ArrayList; | |
import java.util.Random; | |
import java.util.Scanner; | |
public class a6 { | |
public static void main(String[] args) { | |
// 입력받기 | |
Scanner sc = new Scanner(System.in); | |
System.out.print("총 진행할 투표수를 입력해 주세요."); | |
int totalVoteNum = sc.nextInt(); | |
System.out.print("가상 선거를 진행할 후보자 인원을 입력해 주세요."); | |
int candidateNum = sc.nextInt(); | |
ArrayList<String> nameList = new ArrayList<>(); | |
for (int i = 1; i <= candidateNum; i++) { | |
System.out.printf("%d번째 후보자이름을 입력해 주세요.", i); | |
String name = sc.next(); | |
nameList.add(name); // index : i-1 | |
} | |
System.out.println(); | |
ArrayList<Integer> voteArray = new ArrayList<>(); | |
for (int i = 0; i < 10; i++) { | |
voteArray.add(0); | |
} | |
Random random = new Random(); | |
for (int i = 1; i <= totalVoteNum; i++) { | |
int voteNum = random.nextInt(candidateNum); // 0~3 | |
int curNum = voteArray.get(voteNum); | |
voteArray.set(voteNum, curNum + 1); | |
double progressRate = (double) i / totalVoteNum * 100; | |
System.out.printf("[투표진행률]: %.2f%%, %d명 투표 => %s \n", progressRate, i, nameList.get(voteNum).toString()); | |
for (int j = 1; j <= candidateNum; j++) { | |
String candidateNameWithColon = String.format("%-10s", nameList.get(j - 1) + ":"); | |
int candidateVoteNum = voteArray.get(j - 1); | |
double candidateVoteRate = (double)candidateVoteNum / totalVoteNum * 100; | |
System.out.printf("[기호:%d] %-10s %.2f%% \t (투표수: %d)\n", j, candidateNameWithColon, candidateVoteRate, candidateVoteNum); | |
} | |
System.out.println(); | |
} | |
// 당선인 선정 | |
int maxVoteNum = 0, maxCandidateIndex = 0; | |
for (int i = 0; i < candidateNum; i++) { | |
int curVoteNum = voteArray.get(i); | |
if (curVoteNum > maxVoteNum) { | |
maxVoteNum = curVoteNum; | |
maxCandidateIndex = i; | |
} | |
} | |
System.out.printf("[투표결과] 당선인 : %s", nameList.get(maxCandidateIndex)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment