Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Need help with mode methods

joker3000Apr 12 2015 — edited Apr 13 2015

Hi, I got this code with mode methods. The results is not exactly what i have in mind. Please can anyone help me out ?

Code:

import java.util.ArrayList; 

import java.util.Arrays; 

import java.util.List; 

import java.util.Random; 

  import java.util.*; 

public class ProcessMarks { 

    private static final int NMARKS = 125; 

    private static final double mean = 65.0; 

    private static final double std = 15.0; 

 

    public static int[] getMarks() { 

        Random rand = new Random(1001L); 

        int mark; 

        int[] theMarks = new int[NMARKS]; 

        int n = 0; 

        while (n < NMARKS) { 

            mark = (int) Math.round(std * rand.nextGaussian() + mean); 

            if (mark >= 0 && mark <= 100) 

                theMarks[n++] = mark; 

        } 

        return theMarks; 

    } 

 

public static Integer[] mode(int[] getMarks){ 

        List<Integer> modeArray = new ArrayList<Integer>(); 

        int maxCount=0;    

        for (int i = 0; i < getMarks.length; ++i){ 

          int count = 0; 

          for (int j = 0; j < getMarks.length; ++j){ 

            if (getMarks[j] == getMarks[i]) ++count; 

          } 

          if (count > maxCount){ 

            maxCount = count; 

            modeArray.clear(); 

            modeArray.add( getMarks[i] ); 

          } else if ( count == maxCount ){ 

            modeArray.add( getMarks[i] ); 

          } 

        } 

        return modeArray.toArray( new Integer[modeArray.size()] ); 

      } 

public static void main(String[] args) { 

 

 

        int[] marks = getMarks();

        int[] sortMarks = marks.clone();

       

        Arrays.sort(sortMarks);

        Integer[] modeArray = mode(sortMarks);

        for (int i = 0; i < modeArray.length; ++i) { 

            System.out.println(" *Mode is = " + modeArray[i].intValue()); 

}

Result (it's repeat number):

*Mode is = 53

*Mode is = 53

*Mode is = 53

*Mode is = 53

*Mode is = 53

*Mode is = 62

*Mode is = 62

*Mode is = 62

*Mode is = 62

*Mode is = 62

*Mode is = 67

*Mode is = 67

*Mode is = 67

*Mode is = 67

*Mode is = 67

*Mode is = 77

*Mode is = 77

*Mode is = 77

*Mode is = 77

*Mode is = 77

*Mode is = 78

*Mode is = 78

*Mode is = 78

*Mode is = 78

*Mode is = 78

*Mode is = 85

*Mode is = 85

*Mode is = 85

*Mode is = 85

*Mode is = 85

Result that i want it to be (number appear only once):

*Mode = 53, 62, 67, 77, 78, 85


or


*Mode is = 53

*Mode is = 62

*Mode is = 67

*Mode is = 77

*Mode is = 78

*Mode is = 85


THANKS

Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on May 11 2015
Added on Apr 12 2015
12 comments
2,061 views