본문 바로가기
하지의 코딩일지/JAVA TEST

자바 후보자 투표 가상시뮬레이션 테스트

by 하지마지 2023. 7. 8.
728x90
import java.util.Random;
import java.util.Scanner;

public class JavaStudy06 {

// 총 투표수 10,000
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

System.out.print("총 진행할 투표수를 입력해 주세요:");
int total = sc.nextInt();

System.out.print("가상 선거를 진행할 후보자 인원을 입력해주세요:");
int candidatenum = sc.nextInt();

System.out.print("1번째 후보자이름을 입력해 주세요:");
String firstcd = sc.next();
System.out.print("2번째 후보자이름을 입력해 주세요:");
String secondcd = sc.next();
System.out.print("3번째 후보자이름을 입력해 주세요:");
String thirdcd = sc.next();
System.out.print("4번째 후보자이름을 입력해 주세요:");
String fourthcd = sc.next();
System.out.print("5번째 후보자이름을 입력해 주세요:");
String fifthcd = sc.next();

sc.close();

Random random = new Random();
int[] candidate = new int[5];
String[] name = new String[]{firstcd, secondcd, thirdcd, fourthcd, fifthcd};

for (int i = 1; i <= total; i++) {
// 랜덤 투표율을 생성하여 후보자에게 투표를 부여합니다.
int voteRate = random.nextInt(5);
candidate[voteRate]++;

System.out.println();
System.out.printf("[투표진행율]: %05.02f%c, %d명 투표 => %s\n", ((double) candidate[voteRate] / (double) total) * 100.0f, '%', (int) candidate[voteRate], name[voteRate]);

// 각 후보자의 투표 결과를 출력합니다.
for (int j = 0; j < candidatenum; j++) {
System.out.printf("[기호:%d] %4s : %05.02f%c, (투표수: %d)\n", (j + 1), name[j], ((double) candidate[j] / (double) total) * 100.0f, '%', candidate[j]);
}

// 모든 투표가 완료된 후 동률이 있는 경우, 투표를 다시 진행합니다.
if (i == total) {
int max = 0;
for (int j = 0; j < candidatenum; j++) {
if (max < candidate[j]) {
max = candidate[j];
}
}
int same = 0;
for (int j = 0; j < candidatenum; j++) {
if (max == candidate[j]) {
same++;
}
}

if (same > 1) {
i--;
}
}
}

// 가장 많은 투표를 받은 후보자를 선출하여 결과를 출력합니다.
int max = 0;
String victor = "";
for (int i = 0; i < candidatenum; i++) {
if (max < candidate[i]) {
max = candidate[i];
victor = name[i];
}
}

System.out.printf("[투표결과] 당선인: %s\n", victor);
}
}
728x90