Created
June 6, 2023 03:00
-
-
Save dkwktm45/933e0299ee04257a9b704d5766b4725c to your computer and use it in GitHub Desktop.
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.Comparator; | |
import java.util.HashMap; | |
import java.util.Random; | |
import java.util.Scanner; | |
// 이진영 | |
// 미니과제 6번 | |
public class ZeroReport06 { | |
public static void main(String[] args) { | |
Scanner sc = new Scanner(System.in); | |
StringBuffer sb = new StringBuffer(); | |
System.out.print("총 진행할 투표수를 입력해주세요."); | |
int voters = verification(sc, false, 1, 10000); | |
System.out.print("가상 선거를 진행할 후보자 인원을 입력해주세요."); | |
int elector = verification(sc, false, 2, 10); | |
HashMap<Integer,String> indexToName = new HashMap<>(); | |
HashMap<String,Integer> nameToVote = new HashMap<>(); | |
for(int i = 1; i <= elector; i++){ | |
System.out.print((i + 1) + "번째 후보자이름을 입력해 주세요."); | |
String name = sc.next(); | |
if(name.length() >= 10){ | |
System.out.print("허용할 수 없는 후보자 이름입니다. 다시 입력해주세요.(10글자 내)"); | |
name = sc.next(); | |
i--; | |
}else{ | |
indexToName.put(i,name); | |
nameToVote.put(name, 0); | |
} | |
} | |
System.out.println(); | |
Random rd = new Random(); | |
rd.setSeed(System.currentTimeMillis()); | |
System.out.println(); | |
for(int i = 1; i <= voters; i++){ | |
int rdnum = rd.nextInt(elector) + 1; | |
String electorName = indexToName.get(rdnum); | |
sb.append(String.format("[투표 진행률]: %.2f%% , %d명 투표 => %s \n", (double) i / voters * (double) 100.0, i , electorName)); | |
nameToVote.put(electorName, nameToVote.getOrDefault(electorName, 0) + 1); | |
for(int j = 1; j <= elector; j++){ | |
String name = indexToName.get(j); | |
int length; | |
int numResult = 10 - name.length() * 2; | |
if(numResult> 0){ | |
length = numResult; | |
}else{ | |
length = 1; | |
} | |
sb.append(String.format("[기호:%d] %s%-"+length+"s %.2f%% (투표수: %d) \n",j ,name,":", (double) nameToVote.get(name) / (double) voters * 100.0, nameToVote.get(name) )); | |
} | |
} | |
sb.append("[투표결과] 당선인 : " + nameToVote.keySet().stream() | |
.max(Comparator.comparing(nameToVote::get)) | |
.orElse(null)); | |
System.out.println(sb); | |
} | |
public static int verification(Scanner sc , boolean verity,int min ,int max){ | |
int result; | |
do{ | |
result = sc.nextInt(); | |
if(result < min || result > max){ | |
System.out.printf("인원 수에 대해서는 제한이 있습니다.(%d명 초과 및 %d미만입니다.)" , min, max); | |
verity = false; | |
}else{ | |
verity = true; | |
} | |
}while(!verity); | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment