Skip to content

Instantly share code, notes, and snippets.

@ramyo564
Created November 7, 2023 16:23
Show Gist options
  • Save ramyo564/d9001b91812fdb81b3bb50cf56a246c8 to your computer and use it in GitHub Desktop.
Save ramyo564/d9001b91812fdb81b3bb50cf56a246c8 to your computer and use it in GitHub Desktop.
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
HashMap<String, Integer> hashMap = new HashMap<>();
Random random = new Random();
Scanner sc = new Scanner(System.in);
System.out.print("총 진행할 투표수를 입력해 주세요.");
int vote = sc.nextInt();
if (vote >= 1 && vote <= 10000) {
System.out.print("가상 선거를 진행할 후보자 인원을 입력해 주세요.");
int people = sc.nextInt();
if (people >= 2 && people <= 10) {
sc.nextLine();
String[] myArray = new String[people];
for (int i = 0; i < people; i++) {
int count = 0;
while (1 != count) {
System.out.print(i + 1 + "번째 후보자 이름을 입력해 주세요.");
String name = sc.nextLine();
if (name.length() <= 10 && name.matches("^[가-힣]*$")) {
myArray[i] = name;
hashMap.put(name, 0);
count +=1;
} else {
System.out.println("후보자 이름은 한글로만 입력가능하며, 10자 미만으로 입력해야 합니다.");
}
}
}
int n = 1;
while (n <= vote) {
int randomNumber = random.nextInt(people);
String name = myArray[randomNumber];
double votePercent = ((double) n / vote) * 100;
int value = hashMap.get(name);
value++;
hashMap.put(name, value);
System.out.printf("[투표진행률]: %.2f%%, %d명 투표 => %s\n", votePercent, n, name);
for (int i = 0; i < myArray.length; i++) {
String eachName = myArray[i];
int eachVale = hashMap.get(eachName);
double eachVotePercent = ((double) eachVale / vote) * 100;
System.out.printf("[기호:%d] %s: %.2f%% (투표수: %d)\n", i + 1, eachName, eachVotePercent, eachVale);
}
n++;
}
String maxKey = null;
int maxValue = Integer.MIN_VALUE;
for (Map.Entry<String, Integer> entry : hashMap.entrySet()) {
if (entry.getValue() > maxValue) {
maxValue = entry.getValue();
maxKey = entry.getKey();
}
}
System.out.println("[투표결과] 당선인: " + maxKey);
} else {
System.out.println("후보 인원은 2~10 사이의 값이어야 합니다.");
}
} else {
System.out.println("1~10000 사이의 값을 입력 해주세요");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment