如何查找Java EE中数组中重复元素的出现次数?

破坏性玩家:

我尝试编写代码片段以查找Java 1维数组中重复元素的出现次数..计数器似乎没有超过1 ...有人可以帮帮我..这是我的代码:

import java.util.*;
public class duplicate{
    public static void main(String args[]){
        int i,n,c,j,m=-1;
        Scanner a = new Scanner(System.in);
        System.out.println("Enter the value of length");
        n=a.nextInt();
        int b[] = new int[n];
        System.out.println("Enter the elements of the array.");
        for(i=0;i<n;++i)
            b[i]=a.nextInt();
        for(i=0;i<n;++i){
            c=0;
                if(b[i]==m)
                continue;
                else{
                    m=b[i];
                  for(j=0;j<=i;++j){
                   if(b[j]==b[i])
                   c++;
                   
                  }
                  System.out.println("The element"+b[i]+" has occured "+c+" times.");
            }
        }
            
        }
    }
恶棍:

您的代码段中有许多概述。首先,我建议您正确设置代码格式,并可能改善一些变量命名。

我将您的代码部分显示为有问题的:

    for (i = 0; i < n; ++i) {
        c = 0;
        if (b[i] == m) {
            continue;
        } else {
            /*
            * here you always set m to the current value of the array so in the next
            * iteration, your check in the "if clause" will be true what means that the
            * counter will never count up if there are 2 or more consecutive equal numbers
            */
            m = b[i];
            for (j = 0; j <= i; ++j) {
                // also this logic is flawed, because you only count the values
                // before the current one
                if (b[j] == b[i])
                    c++;
            }
            System.out.println("The element" + b[i] + " has occured " + c + " times.");
        }
    }

我宁愿建议您使用此类任务,是使用a HashMap并计算那里每个值的出现次数。

例:

public static void main(String[] args) {

    Scanner scanner = new Scanner(System.in);
    System.out.println("Enter the value of length");
    int size = scanner.nextInt();
    int[] values = new int[size];
    System.out.println("Enter the elements of the array.");
    for (int i = 0; i < size; i++) {
        values[i] = scanner.nextInt();
    }

    Map<Integer, Integer> map = new HashMap<>();
    for (int key : values) {
        if (map.containsKey(key)) {
            int occurrence = map.get(key);
            occurrence++;
            map.put(key, occurrence);
        } else {
            map.put(key, 1);
        }
    }

    for (Integer key : map.keySet()) {
        int occurrence = map.get(key);
        System.out.println(key + " occurs " + occurrence + " time(s).");
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章