Find the element with highest occurrences in an array [java]

后端 未结 11 1630
后悔当初
后悔当初 2021-01-18 02:36

I have to find the element with highest occurrences in a double array. I did it like this:

int max = 0;
for (int i = 0; i < array.length; i++) {
       in         


        
11条回答
  •  长情又很酷
    2021-01-18 03:40

    public static void main(String[] args) {
    
       int n;
    
       int[] arr;
    
        Scanner in = new Scanner(System.in);
        System.out.println("Enter Length of Array");
        n = in.nextInt();
        arr = new int[n];
        System.out.println("Enter Elements in array"); 
    
        for (int i = 0; i < n; i++) {
            arr[i] = in.nextInt();
        }
    
        int greatest = arr[0];
    
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] > greatest) {
                greatest = arr[i];
            }
    
        } 
    
        System.out.println("Greatest Number " + greatest);
    
        int count = 0;
    
        for (int i = 0; i < arr.length; i++) {
            if (greatest == arr[i]) {
                count++;
            }
        }
    
        System.out.println("Number of Occurance of " + greatest + ":" + count + " times");
    
        in.close();
    }
    

提交回复
热议问题