有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java检查三个数组是否具有相同的值

我把三个人的数字放在一个arraylist中,如果三个人的数字相同,那么总体上occurrences++;这是我的算法,但它不适用于这种情况

5 (first person has 5 nums)
13 20 22 43 146

4 (second person has 4 nums)
13 22 43 146

5 (third person has 5 nums)
13 43 67 89 146

int occurrences = 0;
for (int i = 0; i<n; ++i){
    for (int j = n; j<n+b; ++j ){
        if(arr.get(i)==arr.get(j)){
            System.out.println(arr.get(i)+" " +arr.get(j));
            for(int k=n+b; k<arr.size(); ++k){
                if(arr.get(j)==arr.get(k)){
                    ++occurrences;
                    System.out.println(arr.get(k));
                }
            }
        }
    }
}

共 (1) 个答案

  1. # 1 楼答案

    如果你有3人3组,试试这个

    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter numbers for 1st person seprated by ',' like 1,2,3....");
        String noForFirst = sc.nextLine();
        String[] a = noForFirst.split(",");
        System.out.println("Enter numbers for 2nd person seprated by ',' like 1,2,3....");
        String noForSecond = sc.nextLine();
        String[] b = noForSecond.split(",");
        System.out.println("Enter numbers for 3rd person seprated by ',' like 1,2,3....");
        String noForThird = sc.nextLine();
        String[] c = noForThird.split(",");
        int occurrences = 0;
        for (int i = 0; i < a.length; ++i) {
            for (int j = 0; j < b.length; ++j) {
                if (a[i].equals(b[j])) {
                    for (int k = 0; k < c.length; ++k) {
                        if (a[i].equals(c[k])) {
                            ++occurrences;
                            System.out.println(a[i]);
                        }
                    }
                }
            }
        }
        System.out.println("occurrences = " + occurrences);
    

    输入

    Enter numbers for 1st person seprated by ',' like 1,2,3.... 1,5,9,7,6 Enter numbers for 2nd person seprated by ',' like 1,2,3.... 1,4,8,7,3,5 Enter numbers for 3rd person seprated by ',' like 1,2,3.... 1,7,2

    输出

    1 7 occurrences = 2