Problem with sorting array and fiding most frequently occuring exam


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 4 of 4

Thread: Problem with sorting array and fiding most frequently occuring exam

  1. #1
    Join Date
    Dec 2006
    Posts
    2

    Problem with sorting array and fiding most frequently occuring exam

    I am having problems sorting the names array to print the data alphabetically going by the first names.

    Also I cannot seem to figure out how to find the most frequently occuring exam out of the given scores.

    Code:
    import java.awt.*; 
    import java.net.*; 
    import java.io.*; 
    import java.awt.event.*; 
    import javax.swing.*; 
    
        public class Project4
        {  
            public static String out = "";                  //holds value of print line
            public static float []avg = new float [5];
            public static String Highgrade = " ";
            public static String [] names = {"Mary     ", "John     ", "William", "Debbie ", "Ralph    "};   //assigns 5 names to string 
            public static String highname = " "; 
            public static String HighExam = " ";
            public static String grade = " ";
            public static float [] weight = {132, 165, 200, 155, 145};
        
        public static void main (String [] args)
        {
            int [] temp = {34,24,78,65,45,100,90,97,56,89,78,98,74,90,98,24,45,76,98,54,12,20,22,55,66};
            int [][]score = new int [5][5];                                                     //will hold scores 
            //int most _freq_exam = find_most_freq_exam(scores);
     
            //String high_student = find_best_stu (names,scores);
            //String grade = "";                                                                  //Holds value of each persons scores
            String message = ("Name           Weight         Average           Scores    \n");
            int c = 0;
            for (int a=0;a<=4;a++)                                                              //following lines of codes put
            {                                                                                   //  grades in 2D Array
                for (int b=0; b<=4;b++)                     
                {
                    score[a][b] = temp[c];
                    c++;
                }
            }
        
        out = compute_avg (score, names);
        HighExam = Highest_Exam (score, names);
        Highgrade = Weight (score, weight);
        JOptionPane.showMessageDialog (null,message +out + "\n\n" + HighExam + "\n\n" + Highgrade);
        System.exit(0);
        
        } 
        public static String Highest_Exam (int score[][], String names[])
        {
            int high = 0;
            for (int a = 0; a<=4; a++)
                for (int b = 0; b<=4; b++)
                    {
                        if (score[a][b] >= high)
                        {
                            high = score [a][b];
                            highname = names[a];
                        }
                    }
            HighExam = "With a Score of" + high + ", the Student with the Highest Score is " + highname;
            return HighExam;
        }
        public static String compute_avg (int score[][], String names[]) //need to sort by row, prior to the for statement
        { 
            int high = 0; 
            int highscore = 0; 
            
            
           int m,n,x,z = 0;
           for (z=0;z<3;z++)
           {
            for (m=0;m<=4;m++)
            {for (n=0;n<=3;n++)
                {if (score[m][n]>score[m][n+1])
                   { x=score[m][n+1]; 
                    score[m][n+1]=score[m][n];
                    score[m][n]=x;
                }x=0;
                }
            }
        }
            
            for (int d = 0; d<=4; d++)                                                          //puts names and scores together 
            { 
                avg[d] = 0; 
                for (int e=0;e<=4;e++)                                                          //loop that controls score 
                { 
                    grade = score [d][e] + " " + grade;                                         //Puts all five scores in a String 
                    avg[d] = avg[d] + score [d][e]; 
                    if (score[d][e] >= high) highscore = score[d][e];                           //Determines high score for all individuals 
                } 
                avg[d] = (avg[d] - score[d][2] + highscore)/5; 
                 
                out = out + names[d] + "         " + weight[d] + "          " + avg [d] + "             " + grade + "\n"; 
                grade = ""; 
            } 
            return out; 
        } 
    
        public static String Weight (int score[][], float weight [])        //determines the weight of each person and tallys the number of
        {                                                                   //70,80, and 90 scores for 150+ and <150 
                int thincnt = 0;                                            // counters for scores and weights
                int fatcnt = 0;
                int cntA = 0;
                int cntB = 0;
                int cntC = 0;
                int cntD = 0;
                int cntE = 0;
                int cntF = 0;
                           
                for (int a =0; a<=4; a++)
                {
                   if (weight[a] >= 150) 
                   {
                       fatcnt = fatcnt + 1;
                       for (int b=0; b<=4; b++)
                        {
                            if (score [a][b] >= 90 && score [a][b] <= 99) { cntA = cntA+1; 
                            } else if (score [a][b] >= 80 && score [a][b] <= 89) { cntB = cntB+1;
                            } else if (score [a][b] >= 70 && score [a][b] <= 79) cntC = cntC+1;
                        }
                    } else {if (weight[a] <= 150) 
                        {
                            thincnt = thincnt + 1;
                            for (int c=0; c<=4; c++)
                            {
                            if (score [a][c] >= 90 && score [a][c] <= 99) { cntD = cntD+1; 
                            } else if (score [a][c] >= 80 && score [a][c] <= 89) { cntE = cntE+1;
                            } else if (score [a][c] >= 70 && score [a][c] <= 79) cntF = cntF+1;
                        }
                Highgrade = "There are " + fatcnt + " fat people.  Their scores are:      "+ cntA + " - in the 90's     " + cntB + " - in the 80's     " + cntC + " - in the 70's" + "\n" + "\n" +
                          "There are " + thincnt + " thin people.  Their scores are:     "+ cntD + " - in the 90's     " + cntE + " - in the 80's     " + cntF + " - in the 70's" + "\n";
                                }}}
                return Highgrade;
                    }
              }
    Last edited by kmcconn9; 12-06-2006 at 10:46 PM.

  2. #2
    Join Date
    Feb 2006
    Location
    Cologne - Germany
    Posts
    271
    to sort alphabetically you need a collator-object, which itself implements the comparator interface specially for sorting alphabetically.
    have a look at the javadocs and use it with the appropriate sort method in class arrays (sort(Object[] a, Comparator c) ) with the collator as the comparator.

    but your implementation is not object-oriented and will make problems. when you sort the names array, it will be sorted, but this will not equally sort the weights. what#s missing is a connection between the names and the other attributes of the "person".

    make a object for your person containing all data to that person like:
    Code:
    public class Person{
      private String name;
      private float weight;
     ...
    
      public String getName(){
        return name;
      }
    
      public float getWeight(){
        return weight;
      }
    }
    this way, all information is contained within an object.

    now you can create an array of Persons and sort it through special comparators,
    which act on special attributes.

    a sorting for the weight would look like this:

    Code:
    public WeightComparator implements Comparator{
      public int compare(Object a, Object b){
        Person pa = (Person) a;
        Person pb = (Person) b;
        if (pa.getWeight()==pb.getWeight()) return 0;
        else if (pa.getWeight()>pb.getWeight()) return 1;
        return -1;
      }
    }
    Code:
    Arrays.sort(personsArray, new WeightComparator());
    that's the right strategy. you can implement comparators for any attribute of person. for names, you will have to use a collator:

    Code:
    public NameComparator implements Comparator{
      private Collator collator = Collator.getInstance();
      public int compare(Object a, Object b){
        Person pa = (Person) a;
        Person pb = (Person) b;
        return collator.compare(pa.getName(), pb.getName());
      }
    }
    that's it.

  3. #3
    Join Date
    Dec 2006
    Posts
    2
    hmm I will give that a try. Thanks for your input. I believe that there should be a way that you can do the sort with various for loops.

    For instance, you would have to create a third variable to hold the value so you wouldnt loose the value your were flipping...

    Any ideas on the frequency of most occuring grade?
    Last edited by kmcconn9; 12-07-2006 at 07:36 AM.

  4. #4
    Join Date
    Dec 2004
    Location
    San Bernardino County, California
    Posts
    1,468
    Here's a procedural type method for your most frequently occurring grade issue: use an array (scores) of 101 ints, (0 to 100) all initialized to 0, read through your scores, increment the value at score

    Code:
    scores[score] = scores[score] + 1;
    then read your array through for maxScore:

    Code:
    int maxScore = score[0];
    int maxElement = 0;
    for( int i = 1; i < 101; ++i )
    {
        if ( scores[i] > maxScore )
        {
            maxScore = scores[i];
            maxElement = i;
        }
    }
    The score with the most occurrences is maxElement.


    Take a look at your field(variable) names. It is the convention in Java for variables (and methods) to start with a lowercase letter. A name which starts with an uppercase letter is reserved for classes. This may seem like quibbling, but it makes your code more understandable and less confusing to a person reading it if you follow convention. So you should be using highGrade, highExam, highest_Exam(), weight().

    Also ... another quibble ... why are you writing this class with all public and all static methods? Is it because you get errors when you compile unless the methods are static? You are ignoring OOP design.
    Last edited by nspils; 12-07-2006 at 08:23 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center