【问题标题】:How to check if all elements of a arrayList is the same?如何检查arrayList的所有元素是否相同?
【发布时间】: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


【解决方案1】:

尝试使用您所做的将 tie case 设置为 true,例如:

else if (tie == true) { System.out.println("no winner"); }

【讨论】:

  • if (tie) { - 布尔型,可以直接使用
猜你喜欢
  • 2014-01-22
  • 1970-01-01
  • 2011-04-20
  • 2011-01-19
  • 1970-01-01
  • 1970-01-01
  • 2021-01-03
  • 2019-01-09
  • 2012-05-04
相关资源
最近更新 更多