描述
请实现一个计票统计系统。你会收到很多投票,其中有合法的也有不合法的,请统计每个候选人得票的数量以及不合法的票数。
(注:不合法的投票指的是投票的名字不存在n个候选人的名字中!!)
数据范围:每组输入中候选人数量满足 1 \le n \le 100 \1≤n≤100 ,总票数量满足 1 \le n \le 100 \1≤n≤100
输入描述:
第一行输入候选人的人数n,第二行输入n个候选人的名字(均为大写字母的字符串),第三行输入投票人的人数,第四行输入投票。
输出描述:
按照输入的顺序,每行输出候选人的名字和得票数量(以" : "隔开,注:英文冒号左右两边都有一个空格!),最后一行输出不合法的票数,格式为"Invalid : "+不合法的票数。
示例1
输入:
4 A B C D 8 A D E CF A GG A B复制输出:
A : 3 B : 1 C : 0 D : 1 Invalid : 3复制说明:
E CF GG三张票是无效的,所以Invalid的数量是3.
package org.example.simple;
import java.util.*;
public class Hj94 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
int n = scanner.nextInt();
scanner.nextLine();
String s = scanner.nextLine();
String[] s1 = s.split(" ");
String[] people = new String[n];
for (int i = 0; i < n; i++) {
people[i] = s1[i];
}
Map<String, Integer> maps = new LinkedHashMap<>();
for (int i = 0; i < people.length; i++) {
maps.put(people[i], 0);
}
int vote = scanner.nextInt();
scanner.nextLine();
String s2 = scanner.nextLine();
String[] s3 = s2.split(" ");
List<String> votePeople = new ArrayList<>();
for (int i = 0; i < vote; i++) {
votePeople.add(s3[i]);
}
List<String> votePeopleCopy = votePeople;
int invalidCount = 0;
for (int i = 0; i < people.length; i++) {
int count = countStr(votePeople, people[i]);
if (count!=0){
maps.replace(people[i], maps.get(people[i]), maps.get(people[i]) + count);
votePeopleCopy = removeDuplicateRecords(votePeopleCopy, people[i]);
}
}
maps.put("Invalid", votePeopleCopy.size());
for (Map.Entry<String, Integer> stringIntegerEntry : maps.entrySet()) {
System.out.println(stringIntegerEntry.getKey() + " : " + stringIntegerEntry.getValue());
}
}
}
public static int countStr(List<String> list, String keyWord) {
int count = 0;
for (String s : list) {
if (s.equals(keyWord)) {
count++;
}
}
return count;
}
public static List<String> removeDuplicateRecords(List<String> list, String str){
List<String> nlist = new ArrayList<>(list.size());
for (String s : list) {
if(!s.equals(str)){
nlist.add(s);
}
}
return nlist;
}
}