Unit 8 Projects

Project 1 Worker class:

A Worker has the following three fields:

String name, int yearsOfExperience, booealn degreeInField

Provide:

1)  an initialize constructor

2) accessors/modifiers

3) equals method that overrides the method from Object class

4) toString method

 

 

Job class:

A job “has-an” array of Worker objects.

Provide:

1) An initialize constructor (make sure to copy values into field)

2) accessors

3) a method called nameOfWorkerWithMostExperience that returns the name of the worker who has the most years of experience

4) a method called averageYearsOfExperience that returns the average years of experience for the workers

5) a method called numberOfYearsAboveAverage that returns an array of double values that represent how many more years the worker has worked than average

i.e. worker hours: 5, 15, 8, 12, 20

method should return -7, 3, -4, 0, 8

6) a toString method that displays all the workers at the Job.  Take advantage of the toString method supplied for the Worker class.


Project 2 Gradebook Class

Gradebook Project

Create a class called Test.  A Test object will contain the grade scored on the Test and whether the student completed the H.W. for the test.

Test probability = new Test(85, true);

The above example represents a student completing the HW for the test and earning an 85 on the test.

Provide a) no-args constructor and initialize constructor

           b) accessors and modifiers

               toString() method that returns (for example: grade = 85, h.w. = true)

Gradebook class:

A Gradebook will have one field: private Test[][] tests;

Each row of the 2-D array represents the grades for a single student for a given year.

i.e.

85, true 70, false 65, false 77, true

98, true 79, true 60, false 65, false

88, false 88, true 80, true 90, true

…..

….

….

….

 

Gradebook class should provide an initialize constructor.  The constructor will accept a 2-D array of Test objects and initialize the field.  Remember you should copy the elements in this array, not just assign the dummy variable to the field (understand why).

The Gradebook class should have the following methods:

double[] studentAverages()//returns the averages for each student

double[] testAverages()//returns the averages for each test

int indexOfHighestStudent()//returns the index of the student with the highest average

int indexOfLowestTest()//returns the index of the test that has the lowest average

int highestTest()//returns the grade of the highest test from any assignment

(i.e. = 98 from the example above)

boolean didLowestTestStudentDoHw()//returns true if the student with the very lowest test attempted the h.w. for the test

double differenceInAveragesBetweenHWAndNoHW()//returns the difference in the average test grade for students who completed HW vs. students who did not complete HW.


Project 3 

Candidate class

private String name;

private int yearsofExperience;

private boolean degreeInField;

private double salaryExpectation; //in $ per hour

 

Initialize Constructor

 

Accessors/Modifiers

 

int value() // Candidates are more valuable if they have more years of Experience and a degree in field.  Having a degree in the field is worth 50 points and then 5 points for every year of experience.

 

String toString()

 

i.e. Craig Sapp has a degree in field with 8 years of experience.

 

 

Interview class:

 

private ArrayList<Candidate> candidates;

 

Initialize constructor

 

Accessors/Modifiers

 


Candidate getHighestValuedCandidate()

 

double getAverageYearsOfExperience()

 

double getLowestSalaryExpectation()

 

String toString()

 

//Jeff Johnson is the winning candidate.  He has 4 more years of experience than the average and expects to be paid $24 an hour.


Project 4: PIXLAB (done together in class)


Project 5: 


import java.awt.*;

import java.util.*;

public class Tester

{

    public static void main(String[] args)

    {

        ArrayList<Color> colors = new ArrayList<Color>();

        colors.add(new Color(200, 200, 100));

        colors.add(new Color(150, 160, 110));

        colors.add(new Color(90, 80, 70));

        colors.add(new Color(100, 110, 50));

        System.out.println(closestToGray(colors));

    }

    

    public static Color closestToGray(ArrayList<Color> cs)

    {

       //implement code here to return the Color object in cs that is closest to gray (i.e. smallest range between red, green, and blue)

       //The Color above that is closest to gray would be 90, 80, 70

   }


Project 6: 


Create a class called Student that implements a compareTo method.

Students will have three fields: First Name, Last Name, and Period

The class should compare this student to another by comparing their period number; if they are equal it should compare their last names; if they are equal it should compare their first names

Copy the following tester class:

import java.util.ArrayList;

 

public class StudentTester

{

public static void main(String[] args)

    {

      ArrayList<Student> students = new ArrayList<Student>();

      students.add(new Student("Jeff", "Adams", 1));

      students.add(new Student("Jill", "Henderson", 3));

      students.add(new Student("Craig", "Taylor", 5));

      students.add(new Student("Joe", "Thomas", 1));

      students.add(new Student("Betsy", "Durrence", 1));

      students.add(new Student("Dina", "Jenkins", 5));

      students.add(new Student("Thomas", "Clowney", 1));

      students.add(new Student("Tracey", "Martin", 1));

      students.add(new Student("Ted", "Sapp", 5));

      students.add(new Student("Brianna", "Sapp", 5));

      students.add(new Student("David", "Medrano", 3));

      students.add(new Student("Brianna", "Brunson", 5));

      students.add(new Student("Peter", "Keevey", 1));

      students.add(new Student("Jan", "Martin", 1));

}

}

 

·         Create an array (not ArrayList) called students2.  Copy all the student from the students ArrayList in to the students2 array.

·         Create a student   Student a = new Student(“Joe”, “Thomas”, 1);

·         Create a method in the tester class called sequentialSearch.

·         Call the method sequentialSearch to search the students ArrayList for Student a.  It should return and print 3.

·         Create a method in the tester class called selectionSort

·         Sort the students in the students ArrayList.

·         Print out the sorted students ArrayList to see that they are first sorted by period and then by last name and then by first name

·         Create a method in the tester class called binarySearch.

·         Call the method binarySearch to search the students ArrayList for Jill Henderson from 3rd period.

·         Create a method in the tester class called insertionSort

·         Sort the students in the students2 array.

·         Print out the sorted students2 array to see that they are first sorted by period and then by last name and then by first name


Project 7: 

Define a class Diploma and its subclass DiplomaWithHonors, so that the statements

             Diploma diploma1 = new Diploma(“Murray Smith”, “Gardening”);

             System.out.println(diploma1);

             System.out.println();

 

             Diploma diploma2 = new DiplomaWithHonors(“Lisa Smith”, “Evolutionary Psychology”);

             System.out.println(diploma2);

 

Display

 

This certifies that Murray Smith

has completed a course in Gardening

 

This certifies that Lisa Smith

has completed a course in Evolutionary Psychology

*** with honors ***

 

Make your class definitions consistent with the information-hiding principle and avoid duplication of code.


Project 8: Board Class

Create a class called Board.  A Board has two int fields: numRows and numCols

Supply an initialize constructor and a no-args constructor (default: 3x3)

Supply accessor(s) and modifier(s)

Create a method called numberOfCells that returns the number of cells on the board.

Create a method called printBoard() that prints the board (nulls everywhere)

Overload the method printBoard by supplying a printBoard method that accepts two integers: int r and int c.  The method should print the board as before but place an “X” at (r,c).

Create a method called placeRandomXOnRowR.  The method accepts one integer: int r.  The method should print the board as before but place an “X” at a random column on row r.


Project 9: ThreeDiceGame:



You are to play a game in which you roll a die three times and get a certain number of points for the game.  You have to choose one of three strategies to determine how many points you will receive.

Strategy 1: roll three dice and add the number of pips on the dice and subtract 2 to get your score.

Strategy 2: roll three dice until you get three odd numbers.  The number of tries it takes you to get three odds will be your score.

Strategy 3: roll three dice and find the largest difference between any two of the die.  Triple this difference to get your score.


** Note:  I tried to come up with weird scenarios so it would be hard to use math and logic determine which one would be best.

 

Die class:

public class Die

{

private int numPips;

public Die() {numPips = 0;}

public void roll() {numPips = (int)(Math.random()*6) + 1;

public String toString() {"num pips = " + numPips;}

}

ThreeDiceGame:

Constructor: takes in a strategy

Fields:

3 Die objects

int score

int strategy

 

Methods:

Accessors

void roll() //rolls all three dice

void play() //plays game and sets score appropriately

double getAverageScore() //approximates the average score of playing the game

 

In Tester class:

 

a) Determine which strategy produces the highest average score.

 

B) If you were to play against another player and whoever gets the highest score wins, which method would you choose?  For this, it could be the one with the highest average but it really is the strategy that wins head-to-head the most.

 



Project 10: Student OOP Project

Student class:

Attributes:

private String name;

private int ID;

private int gradeLevel;

private int numAPsTaken;

private boolean isMale;

  

Provide: Initialize constructor, accessors, modifiers, , goToNextGrade method and a toString method.

The toString method should return in the form:

Name: Jack

ID: 13893

Grade Level: 11

Number of AP Classes Taken: 2

Gender: Male

 

public void goToNextGrade()

if a student is not a senior, the student goes to the next grade level.

 

SAAStudent class  IS-A Student

 

Attributes:

 

private String artsMajor;

private static int numAPsOffered;

 

Provide: Initialize constructor, accessors, modifiers, and a toString method


Note: accessor and modifier should have keyword static for numAPsOffered.

 

The toString should return in the form:

 

Name: Jack

ID: 13893

Grade Level: 11

Number of AP Classes Taken: 2

Gender: Male

Arts Major: Visual

 


Override goToNextGrade.  If a senior goes to the next grade,  the grade level should become -1.


Copy this code into StudentTester class and analyze the results.

 

public class StudentTester

{

public static void main(String[] args)

{

    SAAStudent a = new SAAStudent("Andy", 1, 11, 3, true, "visual");

    SAAStudent b = new SAAStudent("Bob", 2,10,2, true, "orchestra");

    SAAStudent c = new SAAStudent("Cindy",3,11,4, false,"dance");

   

       a.setNumAPsOffered(5);

    System.out.println(a.getNumAPsOffered());

       System.out.println(b.getNumAPsOffered());

       System.out.println(c.getNumAPsOffered());

   

   

}

}

 

1)      Write in words what you think a static variable is?

 

Add these lines at the end of the main method:

a.setNumAPsOffered(7);

System.out.println(a.getNumAPsOffered());

System.out.println(b.getNumAPsOffered());

System.out.println(c.getNumAPsOffered());

System.out.println(SAAStudent.getNumAPsOffered());

 

2)      Why do you think java allows users to call static methods from the class and not an object of the class (i.e. SAAStudent.getNumAPsOffered())?

 

 

 

 

 

 

 

3)      Can you change a static variable?

 

 

4)      What class have we worked with this whole year that ONLY has static methods?


 

public class StudentTester

{

public static void main(String[] args)

{

    //SAAStudent a = new SAAStudent("Andy", 1, 11, 3,true, "visual");

    //Student b = new Student("Bob", 2,12,4,true);

    //SAAStudent c = new Student("Cindy", 2, 10,5,false, "dance");

    //Student d = new SAAStudent("Dana", 4,11,2,false,"chorus");

}

}

 

5)      Uncomment one at a time and determine which instantiations are valid.  What determines whether a “mixed” object reference is valid?

 

 

 

 

 

 

Copy:

public class StudentTester

{

public static void main(String[] args)

{

    Student a = new SAAStudent("Amy", 4,12,2,false,"chorus");

    a.goToNextGrade();

    System.out.println(a.getGradeLevel());

}

}

 

6)      What does this code tell you about the “mixed” object references?  This is called polymorphism.

 

 

 

 

 


 

Copy:

 

public class StudentTester

{

public static void main(String[] args)

{

    Student a = new SAAStudent("Amy", 4,12,2,false,"chorus");

       a.setArtsMajor("dance");

       System.out.println(a.getArtsMajor());

}

}

 

7)      What does this code tell you about the “mixed” object references? 

 

 

 

Copy:

public class StudentTester

{

public static void main(String[] args)

{

    Student a = new SAAStudent("Amy", 4,12,2,false,"chorus");

    Student b = new Student("Bob", 5,12,3,true);

    Student c = new SAAStudent("Cindy",6,11,3,false,"dance");

    Student d = new Student("Dan", 7, 10,0,true);

   

    Student[] students = {a,b,c,d};

   

}

}

 

8)      What does this code tell you about the “mixed” object references?

 

 

 

9)      Could we set the set the arts major of every Student in students?

 

 

 

10)   Could we set increase the ID for every student in students?

 

 

 

11)   Could we tell every student to goToNextGrade?

 

 


 

 

public class StudentTester

{

public static void main(String[] args)

{

    Student a = new SAAStudent("Amy", 4,12,2,false,"chorus");

    Student b = new Student("Bob", 5,12,3,true);

    Student c = new SAAStudent("Cindy",6,11,3,false,"dance");

    Student d = new Student("Dan", 7, 10,0,true);

   

    Student[] students = {a,b,c,d};

    for (Student s: students)

    {

           s.goToNextGrade();

     }

   

     for (Student s: students)

    {

           System.out.println(s.getGradeLevel());

     }

}

}

 

Before you run the code, think about what should get printed.  Write it here.

 


 

Write up:

 

1)      What is a static variable?

 

2)      What is the rule for creating “mixed” object references?

FirstType a = new SecondType(parameter list)

 

3)      if a method is called on object a (that exists in FirstType class), java calls the most recent version of this method.  Meaning if the method is overridden in SecondType class, it calls the method from the SecondType class.  This is called __________________.

 

4)      True or false:  Object a can only call methods that exist in FirstType class

 

5)      What is one advantage of creating “mixed” object references?


Project 11:



public  class Shape

{

    public double getPerimeter() {return 1;}

    

    public double getArea() {return 1;}

    

    public double getRatio() {return getArea()/getPerimeter();}

}


Note: There are no fields in Shape.  Since no constructor is supplied, Java provides a no-args constructor and sets any fields to the default values.


Task: Create three subclasses of Shape (Rectangle which has a length and width, Circle which has a radius, RightTriangle which has two legs)

Override the getPerimeter and getArea methods but not the getRatio method.


In addition: Implement a getDiagonal method in the Rectangle class.


import java.util.*;

public class Test

{

    public static void main(String[] args)

    {

        Shape a = new Rectangle(6,8);

        Shape b = new Circle(5);

        Shape c = new RightTriangle(5,12);

        System.out.println(a.getDiagonal()); //Why does this not work?  Delete the line once you understand.

        

        ArrayList<Shape> shapes = new ArrayList<Shape>();

        shapes.add(a);

        shapes.add(b);

        shapes.add(c);

        

        for (Shape s: shapes)

        {

            System.out.println(s.getRatio());

        }

        

    }

    

 }


Before you run the code, think about what should be printed out.  Remember the getRatio method gets inherited by the three subclasses.