【发布时间】:2020-01-23 13:06:58
【问题描述】:
我正在制作一个程序,该程序将根据谁是获胜者进行打印。 (有关更多详细信息 链接中的任务)https://open.kattis.com/problems/vote
我无法以正确的值打印出“没有赢家”。只有当我的 arrayList 中的所有元素都相同时,我才试图打印出“没有赢家”。前任。
arr = [10, 10, 10]
然后打印出来:
"no winner"
如何检查 arrayList 中的所有元素是否相等?
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class B {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int testCase = sc.nextInt();
for (int i = 0; i < testCase; i++ ) {
int candidate = sc.nextInt();
int maximum = 0;
int winner = 0;
boolean tie = false;
ArrayList<Integer> votes = new ArrayList<>();
for (int j = 0; j < candidate; j++) {
int nVotes = sc.nextInt();
votes.add(nVotes);
}
int imax = votes.indexOf(Collections.max(votes));
int max = Collections.max(votes); // max winner
int in = votes.indexOf(votes);
int index = imax + 1;
int sum = 0;
for(int o = 0; o < votes.size(); o++)
{
sum = sum + votes.get(o);
if (votes.get(o) == votes.get(o) ) {
tie = true;
}
}
if (max > (sum / 2)) {
System.out.println("majority winner " + index);
}
else if (max < (sum / 2)) {
System.out.println("minority winner " + index);
}
else if (votes.get(i) == votes.get(i)) {
System.out.println("no winner");
}
}
}
}
【问题讨论】:
-
votes.stream().distinct().count() == 1. -
你也可以
Collections.max(Arrays.asList(votes)) == Collections.min(Arrays.asList(votes)) -
将列表收集到一个集合中并比较其大小。
new HashSet(votes).size() == votes.size()
标签: java arrays arraylist printing