Write a mode method in Java to find the most frequently occurring element in an array

前端 未结 14 2528
清酒与你
清酒与你 2020-11-29 07:17

The question goes:

Write a method called mode that returns the most frequently occurring element of an array of integers. Assume that the array has at le

14条回答
  •  星月不相逢
    2020-11-29 07:37

    THIS CODE CALCULATES MODE, MEDIAN, AND MEAN. IT IS TESTED AND IT DOES WORK. It is a complete program from start to finish and will compile.

    import java.util.Arrays;
    import java.util.Random;
    import java.math.*;
    /**
     *
     * @author Mason
     */
    public class MODE{
    
        public static void main(String args[])
        {
            System.out.print("Enter the quantity of random numbers  ===>>  ");
            int listSize = Expo.enterInt();
            System.out.println();
            ArrayStats intStats = new ArrayStats(listSize);
            intStats.randomize();
            intStats.computeMean();
            intStats.computeMedian();
            intStats.computeMode();
            intStats.displayStats();
            System.out.println();
        }
    }
    
    
    class ArrayStats
    {
    
        private int list[];
        private int size;
        private double mean;        
        private double median;      
        private int mode;           
    
        public ArrayStats(int s)//initializes class object
        {
            size = s;
            list = new int[size];
        }
    
        public void randomize()
        {
            //This will provide same numbers every time... If you want to randomize this, you can
            Random rand = new Random(555);
            for (int k = 0; k < size; k++)
                list[k] = rand.nextInt(11) + 10;  
        }
    
        public void computeMean()
        {
                   double accumulator=0;
                   for (int index=0;index= popularity2){
              mode = array_item;
              popularity2 = popularity1;
          }
    
    
          popularity1 = 0;
      }}
    
        public void displayStats()
        {
            System.out.println(Arrays.toString(list));
            System.out.println();
            System.out.println("Mean: " + mean);
            System.out.println("Median: " + median);
            System.out.println("Mode: " + mode);
            System.out.println();
        }
    
    }
    

提交回复
热议问题