View the step-by-step solution to:

It is easier because:

This is the assignment-----------------


While it may appear long at first, this lab is easier than it looks, so stay calm. It is easier because:

  1. it uses material and code that you learned, compiled and ran over a week ago when you studied Module 8,and
  2. below, I give you very explicit directions on what to do for each of the very short methods you need to write.

You will start with my existing Student and StudentArrayUtilities classes from the modules. Then you will modify each of these classes as described below and provide a new test client.

Understand the ApplicationSort Flexibility (Student class)

In week 8, we saw an example of a Student class that provided a compareTwoStudents() method. We needed to define such a method because our sort algorithm (which was in the StudentArrayUtilities (SAU) class) had to have a basis for comparing two Student objects, the foundation of SAUs sorting algorithm. Since a Student is a compound data type, not a double or a String, there was no pre-defined compareTo() available, so we created our own compareTwoStudents(), which was based on the spelling of the last name. You can review those notes to see its definition.

We want to make the sort more flexible in this assignment. Sometimes we want to sort on last name, as we did in the lectures, but other times we may choose to sort on the first name (useful for informal communication) or total points(useful for analyzing statistics). We could go into the compareTwoStudents() method and change its definition to work on first name or total points, but all that does is replace the inflexibility of last name with the inflexibility of some other criteria. So here's the plan: we will provide a static Student class method called setSortKey() which will establish a new sort criteria. A client will invoke it whenever it wants to switch to a new basis for comparison. The client will pass a parameter to setSortKey() telling it which one of the three Student fields it wants future sort algorithms to use.

Console Output (SAU class)

Another change we'll make affects the output modality. Rather than using JOptionPane, we want to make the class "U.I. neutral." So we will replace SAU's printArray() method with a toString() method, and let the client choose how to use that. In our example main() we will be sending the String array to the console, only.

Median (SAU class)

We'll add one more method to our SAU class: double getMedianDestructive( Student[] someArray ). This method will return the median of the totalPoints values in an array. Look up median. It is defined as the "middle-value" and is easily computed, but you first have to sort the array in order to find it. Fortunately, you already have the sort method.

Client

Our client will declare four Student arrays to make sure our median works: one array that had an odd number of students (15), one that has an even number of students (16), one that has a single student and one that has no students(we will define the median of an array with no elements to be 0.0).

We'll test the sortKey and sort algorithm only on the even numbered array, and then we will test our median computation on all four arrays.

The Program Spec

These changes should not be complicated as long as you read carefully and follow directions. New and modified members/methods are all very short, so stay focused and apply what you learned back in week 8.

Additions to the Student Class

We will add the following members to the class in the modules.

Public static int constants (finals):
  • SORT_BY_FIRST = 88
  • SORT_BY_LAST = 98
  • SORT_BY_POINTS = 108

These are the three sort keys that will be used by the client and the class, alike, to keep track of, or set, the sort key.  If the client wants to establish a new sort key, it will pass one of these tokens (say Student.SORT_BY_FIRST) to the setter described next.   I have intentionally made the literal values non-contiguous so you would not rely on their particular values in your logic.  You should be able to change the values without breaking your program (but you don't have to change them; use the three values above).

Private static int:
  • sortKey - this will always have one of the three constants above as its value. Make sure it initially has SORT_BY_LAST in it, but after the client changes it, it could be any of the above constants.

You should supply the following simple public static methods:

  • boolean setSortKey( int key ) -- a mutator for the member sortKey.
  • int getSortKey() -- an accessor for sortKey.
Modification to the Student Class
  • compareTwoStudents( ... ) -- same signatures as in the modules, but now this method has to look at the sortKey and compare the two Students based on the currently active sortKey. A switch statement with three different expressions is all you need, and each expression will be very similar to the one already in the modules (in fact one will be identical). As you saw in the modules, it needs to return an int, which is positive, if the first student is greaterthan the second, negative if less than, and zero if they are the samebased on the current value of sortKey, of course.
Change to the StudentArrayUtilities Class
  • Replace printArray() with toString(). Generate the same kind of String, but instead of sending it to the screen, return it to the client.
  • Add a public static method double getMedianDestructive(Student[] array) - This computes and returns the medianof the total scores of all the students in the array The details are simple, but you have to take them each carefully:
  • Dispose of the cases of an empty array (0 elements) and one-element array. Empty arrays return 0.0, always, and one-element array returns its one and only Student's totalPoints. (This second case can actually be skipped if you handle the next cases correctly, but it doesn't hurt to do it separately, here.)
  • Even-numbered arrays >= 2 elements: find the two middle elements and return their average of their total points.
  • Odd-numbered arrays >= 3 elements: return the total points of the exact middle element.
  • Special Note: This method has to do the following. It must sort the array according to totalPoints in order to get the medians, and that's easy since we already have the sort method. Then it has to find the middle-student's score (e.g., if the array is size 21, the middle element is the score in array[10]after the sort). But, before doing the sort, it also has to change the sortKey of the Student class to SORT_BY_POINTS. One detail, that you may not have thought of, is that, at the very start of the method, it needs to save the client's sort key. Then, before returning, restore the client's sort key. This method doesn't know what that sort key might be, but there is an accessor getSortKey() that will answer that question.
  • This method has the word "Destructive" in its name to remind the client that it may (and usually will) modify the order of the array, since it is going to sort the array by total points in the process of computing the median. However, it will not destroy or modify the client's sortKey when the method returns to client (see previous bullet).
The Foothill main()

Our client will declare four Student arrays: using direct initialization, as in the modules: no user input. The array sizes should be 15, 16, 1 and 0. The second array can be the same as the first with one extra Student tagged onto the end. Each array should be initialized in no particular order: unsorted in all fields.

Using the largest, even numbered, array:

  1. display the array immediately before calling a sort method,
  2. sort the array using the default (initial) sort key and display,
  3. change the sort key to first name, sort and display,
  4. change the sort key to total score, sort and display,
  5. setSortKey() to first name, call the getMedianDestructive() method and display the median score. and finally
  6. call getSortKey() to make sure that the getMedianDestructive() method preserved the client's sortKey value of first name that was just set prior to the getMedianDestructive() call.

Using each of the other three arrays:

  • get the median of each array and display. No other testing needed in this part.

Here's a sample output, but you must not use my arrays. Make your own as per the spec above.

Before: 
  smith, fred points: 95
  bauer, jack points: 123
  jacobs, carrie points: 195
  renquist, abe points: 148
  zz-error, trevor points: 108
  perry, fred points: 225
  loceff, fred points: 44
  stollings, pamela points: 452
  charters, rodney points: 295
  cassar, john points: 321

Sorting by default ---------------
After: 
  bauer, jack points: 123
  cassar, john points: 321
  charters, rodney points: 295
  jacobs, carrie points: 195
  loceff, fred points: 44
  perry, fred points: 225
  renquist, abe points: 148
  smith, fred points: 95
  stollings, pamela points: 452
  zz-error, trevor points: 108

Sorting by first name ---------------
After: 
  renquist, abe points: 148
  jacobs, carrie points: 195
  loceff, fred points: 44
  perry, fred points: 225
  smith, fred points: 95
  bauer, jack points: 123
  cassar, john points: 321
  stollings, pamela points: 452
  charters, rodney points: 295
  zz-error, trevor points: 108

Sorting by total points ---------------
After: 
  loceff, fred points: 44
  smith, fred points: 95
  zz-error, trevor points: 108
  bauer, jack points: 123
  renquist, abe points: 148
  jacobs, carrie points: 195
  perry, fred points: 225
  charters, rodney points: 295
  cassar, john points: 321
  stollings, pamela points: 452

Median of evenClass = 171.5
Successfully preserved sort key.
Median of oddClass = 148.0
Median of smallClass = 95.0
Median of noClass = 0.0

Here is the code needed for this assignment

import javax.swing.*;

public class College
{
   public static void main (String[] args)
   {
      Student[] myClass = { new Student("smith","fred", 95), 
         new Student("bauer","jack",123),
         new Student("jacobs","carrie", 195), 
         new Student("renquist","abe",148),
         new Student("3ackson","trevor", 108), 
         new Student("perry","fred",225),
         new Student("loceff","fred", 44), 
         new Student("stollings","pamela",452),
         new Student("charters","rodney", 295), 
         new Student("cassar","john",321),
      };

      StudentArrayUtilities.printArray("Before: ", myClass);
      StudentArrayUtilities.arraySort(myClass);
      StudentArrayUtilities.printArray("After: ", myClass);
   }
}

class Student
{
   private String lastName;
   private String firstName;
   private int totalPoints;

   public static final String DEFAULT_NAME = "zz-error";
   public static final int DEFAULT_POINTS = 0;
   public static final int MAX_POINTS = 1000;

   // constructor requires parameters - no default supplied
   public Student( String last, String first, int points)
   {
      if ( !setLastName(last) )
         lastName = DEFAULT_NAME;
      if ( !setFirstName(first) )
         firstName = DEFAULT_NAME;
      if ( !setPoints(points) )
         totalPoints = DEFAULT_POINTS;   
   }

   public String getLastName() { return lastName; }
   public String getFirstName() { return firstName; } 
   public int getTotalPoints() { return totalPoints; }

   public boolean setLastName(String last)
   {
      if ( !validString(last) )
         return false;
      lastName = last;
      return true;
   }

   public boolean setFirstName(String first)
   {
      if ( !validString(first) )
         return false;
      firstName = first;
      return true;
   }

   public boolean setPoints(int pts)
   {
      if ( !validPoints(pts) )
         return false;
      totalPoints = pts;
      return true;
   }

   // could be an instance method and, if so, would take one parameter
   public static int compareTwoStudents( Student firstStud, Student secondStud )
   {
      int result;

      // this particular version based on last name only (case insensitive)
      result = firstStud.lastName.compareToIgnoreCase(secondStud.lastName);

      return result;
   }

   public String toString()
   {
      String resultString;

      resultString = " "+ lastName 
         + ", " + firstName
         + " points: " + totalPoints
         + "n";
      return resultString;
   }

   private static boolean validString( String testStr )
   {
      if (
            testStr != null && testStr.length() > 0 
            && Character.isLetter(testStr.charAt(0))
         )
         return true;
      return false;
   }

   private static boolean validPoints( int testPoints )
   {
      if (testPoints >= 0 && testPoints <= MAX_POINTS)
         return true;
      return false;
   }
}

class StudentArrayUtilities
{
   // print the array with string as a title for the message box
   // this is somewhat controversial - we may or may not want an I/O
   // methods in this class.  we'll accept it today
   public static void printArray(String title, Student[] data)
   {
      String output = "";

      // build the output string from the individual Students:
      for (int k = 0; k < data.length; k++)
         output += " " + data[k].toString();

      // now put it in a JOptionPane
      JOptionPane.showMessageDialog( null, output, title, 
         JOptionPane.OK_OPTION);
   }

   // returns true if a modification was made to the array
   private static boolean floatLargestToTop(Student[] data, int top)
   {
      boolean changed = false;
      Student temp;

      // compare with client call to see where the loop stops
      for (int k = 0; k < top; k++)
         if ( Student.compareTwoStudents(data[k], data[k + 1]) > 0 )
         {
            temp = data[k];
            data[k] = data[k + 1];
            data[k + 1] = temp;
            changed = true;
         }
      return changed;
   }

   // public callable arraySort() - assumes Student class has a compareTo()
   public static void arraySort(Student[] array)
   {
      for (int k = 0; k < array.length; k++)
         // compare with method def to see where inner loop stops
         if ( !floatLargestToTop(array, array.length - 1 - k) )
            return;
   }
}

Here is my code:

public class Foothill

{

public static void main (String[] args)

{

int k;


    Student[] myClassEven = { new Student("nagamine","kenta", 40),

        new Student("naeem","danyal",324),

        new Student("li","jenna", 132),

        new Student("like","will",222),

        new Student("super","man", 153),

        new Student("shiki","youki",490),

        new Student("yang","rou", 432),

        new Student("sai","rovi", 193),

        new Student("toth","rebecca", 232),

        new Student("johnson","david", 654),

        new Student("jerry","jack", 453),

        new Student("dyon","kub", 244),

        new Student("dark","rachel", 11),

        new Student("don","kou", 312),

        new Student("nishi","haru", 545),

        new Student("yamada","haruna", 764),

    };


StudentArrayUtilities myStudsEven = new StudentArrayUtilities();


for (k = 0; k < myClassEven.length; k++)

myStudsEven.addStudent( myClassEven[k] );


System.out.println( myStudsEven.toString("Before: "));


myStudsEven.arraySort();

System.out.println( myStudsEven.toString("Sorting by default: "));


Student.setSortKey(Student.SORT_BY_FIRST);

myStudsEven.arraySort();

System.out.println( myStudsEven.toString("Sorting by first name: "));


Student.setSortKey(Student.SORT_BY_POINTS);

myStudsEven.arraySort();

System.out.println( myStudsEven.toString("Sorting by total points: "));


System.out.println("Median of evenClass = "

+ myStudsEven.getMedianDestructive() + "n");



    Student[] myClassOdd = { new Student("nagamine","kenta", 40),

        new Student("naeem","danyal",324),

        new Student("li","jenna", 132),

        new Student("like","will",222),

        new Student("super","man", 153),

        new Student("shiki","youki",490),

        new Student("yang","rou", 432),

        new Student("sai","rovi", 193),

        new Student("toth","rebecca", 232),

        new Student("johnson","david", 654),

        new Student("jerry","jack", 453),

        new Student("dyon","kub", 244),

        new Student("dark","rachel", 11),

        new Student("don","kou", 312),

        new Student("nishi","haru", 545)

    };


    // instantiate a StudArrUtilObject

    StudentArrayUtilities myStudsOdd = new StudentArrayUtilities();


    for (k = 0; k < myClassOdd.length; k++)

      myStudsOdd.addStudent( myClassOdd[k] );


    System.out.println( myStudsOdd.toString("Before: "));


    myStudsOdd.arraySort();

    System.out.println( myStudsOdd.toString("Sorting by default: "));


    Student.setSortKey(Student.SORT_BY_FIRST);

    myStudsOdd.arraySort();

    System.out.println( myStudsOdd.toString("Sorting by first name: "));


    Student.setSortKey(Student.SORT_BY_POINTS);

    myStudsOdd.arraySort();

    System.out.println( myStudsOdd.toString("Sorting by total points: "));


    System.out.println("Median of oddClass = "

        + myStudsOdd.getMedianDestructive() + "n");



    Student[] myClassSmall = { new Student("nagamine","kenta", 40)

    };


    StudentArrayUtilities myStudsSmall = new StudentArrayUtilities();


    for (k = 0; k < myClassSmall.length; k++)

      myStudsSmall.addStudent( myClassSmall[k] );


    System.out.println( myStudsSmall.toString("Before: "));


    myStudsSmall.arraySort();

    System.out.println( myStudsSmall.toString("Sorting by default: "));


    Student.setSortKey(Student.SORT_BY_FIRST);

    myStudsSmall.arraySort();

    System.out.println( myStudsSmall.toString("Sorting by first name: "));


    Student.setSortKey(Student.SORT_BY_POINTS);

    myStudsSmall.arraySort();

    System.out.println( myStudsSmall.toString("Sorting by total points: "));


    System.out.println("Median of smallClass = "

        + myStudsSmall.getMedianDestructive() + "n");



    Student[] myClassNo = {};


    StudentArrayUtilities myStudsNo = new StudentArrayUtilities();


    for (k = 0; k < myClassNo.length; k++)

      myStudsNo.addStudent( myClassNo[k] );


    System.out.println( myStudsNo.toString("Before: "));


    myStudsNo.arraySort();

    System.out.println( myStudsNo.toString("Sorting by default: "));


    Student.setSortKey(Student.SORT_BY_FIRST);

    myStudsNo.arraySort();

    System.out.println( myStudsNo.toString("Sorting by first name: "));


    Student.setSortKey(Student.SORT_BY_POINTS);

    myStudsNo.arraySort();

    System.out.println( myStudsNo.toString("Sorting by total points: "));


    System.out.println("Median of smallClass = "

        + myStudsNo.getMedianDestructive() + "n");

}


}


class Student

{

private String lastName;

private String firstName;

private int totalPoints;


public static final String DEFAULT_NAME = "zz-error";

public static final int DEFAULT_POINTS = 0;

public static final int MAX_POINTS = 1000;


public static final int SORT_BY_FIRST = 88;

public static final int SORT_BY_LAST = 98;

public static final int SORT_BY_POINTS = 108;

private static int sortKey = SORT_BY_LAST;


public Student( String last, String first, int points)

{

if ( !setLastName(last) )

lastName = DEFAULT_NAME;

if ( !setFirstName(first) )

firstName = DEFAULT_NAME;

if ( !setPoints(points) )

totalPoints = DEFAULT_POINTS;

}


public String getLastName() { return lastName; }


public boolean setLastName(String last)

{

if ( !validString(last) )

return false;

lastName = last;

return true;

}


  public String getFirstName() { return firstName; }


public boolean setFirstName(String first)

{

if ( !validString(first) )

return false;

firstName = first;

return true;

}


  public int getTotalPoints() { return totalPoints; }


public boolean setPoints(int pts)

{

if ( !validPoints(pts) )

return false;

totalPoints = pts;

return true;

}


  public static int getSortKey() { return sortKey; }


public static boolean setSortKey(int inputKey)

{

if ( !(inputKey == SORT_BY_FIRST || inputKey == SORT_BY_LAST

|| inputKey == SORT_BY_POINTS) )

return false;

sortKey = inputKey;

return true;

}


public static int compareTwoStudents( Student firstStudent, Student secondStudent )

{

int result;


switch (sortKey)

{

case SORT_BY_POINTS:

result = firstStudent.totalPoints - secondStudent.totalPoints;

break;


case SORT_BY_FIRST:

result = firstStudent.firstName.compareToIgnoreCase(secondStudent.firstName);

break;


default:

result = firstStudent.lastName.compareToIgnoreCase(secondStudent.lastName);

break;

}

return result;

}


public String toString()

{

String resultString;


resultString = " "+ lastName + ", " + firstName + " points: " + totalPoints + "n";

return resultString;

}


private static boolean validString( String testStr )

{

if (testStr != null && Character.isLetter(testStr.charAt(0)))

return true;

return false;

}


private static boolean validPoints( int testPts )

{

if (testPts >= 0 && testPts <= MAX_POINTS)

return true;

return false;

}

}


class StudentArrayUtilities

{

public static final int MAX_STUDENTS = 20;


private int numStudents = 0;

private Student[] array = new Student[MAX_STUDENTS];


public String toString( String title )

{

String output = title + "n";


for (int k = 0; k < numStudents; k++)

output += " "+ array[k].toString();


return output;

}


public boolean addStudent(Student stud)

{

if (stud == null || numStudents >= MAX_STUDENTS)

return false;


array[numStudents] = stud;

numStudents++;

return true;

}


public double getMedianDestructive()

{

double median;


if (numStudents == 0)

return 0;

if (numStudents == 1)

return array[0].getTotalPoints();


int oldKey = Student.getSortKey();

Student.setSortKey(Student.SORT_BY_POINTS);

arraySort();


if (numStudents % 2 == 1)

median = array[numStudents / 2].getTotalPoints();

else

median = (array[numStudents / 2 - 1].getTotalPoints() +

array[numStudents / 2].getTotalPoints()) / 2.0;


Student.setSortKey(oldKey);


return median;

}


private boolean floatLargestToTop(int top)

{

boolean changed = false;

Student temp;


for (int k = 0; k < top; k++)

if ( Student.compareTwoStudents(array[k], array[k+1]) > 0 )

{

temp = array[k];

array[k] = array[k+1];

array[k+1] = temp;

changed = true;

}

return changed;

}


public void arraySort()

{

for (int k = 0; k < numStudents; k++)

if ( !floatLargestToTop(numStudents -1-k) )

return;

}

}


How can I improve?

Recently Asked Questions

Why Join Course Hero?

Course Hero has all the homework and study help you need to succeed! We’ve got course-specific notes, study guides, and practice tests along with expert tutors.

-

Educational Resources
  • -

    Study Documents

    Find the best study resources around, tagged to your specific courses. Share your own to gain free Course Hero access.

    Browse Documents
  • -

    Question & Answers

    Get one-on-one homework help from our expert tutors—available online 24/7. Ask your own questions or browse existing Q&A threads. Satisfaction guaranteed!

    Ask a Question