Category Archives: Classwork

OOD: Balloon – CashRegister

Check edmodo.com for
Classwork:
Balloon.java and Tester

Homework:
CashRegister.java and Tester

If you are looking ahead (IYALA):
Screen Shot 2015-02-02 at 10.03.46 AM

Use these libraries, download StdIn.java, StdOut.java, StdDraw.java, and StdAudio.java
Look at Standard output and input.
Redirection and piping.
Standard drawing.
Standard audio.
Graphical user interfaces.
Look at exercises 11 through 16 and work on exercise 17. Submit it to edmodo.com.
Look at exercise 18 and write a program YI_TriTess.java to draw the image below. Submit it to edmodo.com.

triangle4_t

OOD: Rabbit Population

Implement an ADT, RabbitPopulation that simulates the growth of a rabbit population. The rules are as follows:

  • Start with one pair of rabbits
  • Rabbits are able to mate at the age of one month
  • A month later, each female produces another pair of rabbits
  • Assume that rabbits never die and that the female always produces one new pair (one male, one female) every month from the second month on
  • Implement a method waitAMonth that waits for one month, and a method getPairs that prints the current number of rabbit pairs

Calculations by hand

Write a test program that shows the growth of the rabbit population for ten months.
Hint: Keep one instance field for the newborn rabbit pairs and another one for the rabbit pairs that are at least one month old.

OOD: Designing classes: Purse and Coin

Chapter Goals
• To learn how to choose appropriate classes to implement
• To understand the concepts of cohesion and coupling
• To minimize the use of side effects
• To document the responsibilities of methods and their callers with preconditions and postconditions
• To understand the difference between instance methods and static methods
• To introduce the concept of static fields
• To understand the scope rules for local variables and instance fields
Choosing Classes
• A class represents a single concept
• Concepts from mathematics:
Point
Rectangle
Ellipse
• Concepts from real life
BankAccount
Purse
• Actors (end in -er, -or)
StringTokenizer
Random (better called RandomNumberGenerator)
• Utility classes–no objects, only static methods
Math
Cohesion
• A cohesive class has a public interface closely related to the single concept that the class represents
• Cohesion is good.
• This class lacks cohesion:
[spoiler title=’Purse and Coin’]

public class Purse
{
   public Purse(){...} 
   public void addNickels(int count){...} 
   public void addDimes(int count){...} 
   public void addQuarters(int count){...} 
   public double getTotal(){...} 
   public static final double NICKEL_VALUE =0.05; 
   public static final double DIME_VALUE =0.1; 
   public static final double QUARTER_VALUE =0.25; ... 
}
•   It has two concepts: purse and coin
•   Solution: Make two classes:
public class Coin 
{ 
   public Coin(double aValue,String aName){...} 
   public double getValue(){...} 
   ... 
}

public class Purse 
{ 
   public Purse(){...} 
   public void add(Coin aCoin){...} 
   public double getTotal(){...} 
   ... 
} 


[/spoiler]

Coupling
• A class depends on another if it calls one of its methods
• Purse depends on Coin because it calls getValue on coins
• Coin does not depend on Purse
• High Coupling = many class dependencies = a bad thing
• Minimize coupling to minimize the impact of interface changes

Dependency Relationship between Purse and Coin Classes

Screen Shot 2016-03-15 at 11.37.10 PM

High and Low Coupling between Classes

Screen Shot 2016-03-15 at 11.38.59 PM

Accessor and Mutator Classes
• Accessor: does not change the state of the implicit parameter (e.g. getBalance for a bank account)
• Mutator: changes the state of the implicit parameter (e.g. deposit)
• Rule of thumb: Mutator should return void
• Immutable class: all methods are accessors (e.g. String)
Side Effect
• Side Effect: any observable change outside the implicit parameter (i.e. the object calling the method)
• Example: modify explicit parameter (in this case, another object)

public void transfer(double amount, BankAccount other)
{
   balance = balance - amount;
   other.balance = other.balance + amount;
}

• Example: printing in method is a side effect, and should be avoided:

public void deposit(double amount)
{   
   if (amount < 0)
      System.out.println("Bad value");
   . . .
}


Common error: can’t modify primitive type parameters

• void transfer(double amount, double otherBalance)

{
   balance = balance - amount;
   otherBalance = otherBalance + amount;
}

• Won’t work
• Scenario:
double savingsBalance = 1000;
harrysChecking.transfer(500, savingsBalance)

Why is the CashRegister Class Not Cohesive?

[spoiler title=’CashRegister’]

/**
   A cash register totals up sales and computes change due.
*/
public class CashRegister
{
   public static final double QUARTER_VALUE = 0.25;
   public static final double DIME_VALUE = 0.1;
   public static final double NICKEL_VALUE = 0.05;
   public static final double PENNY_VALUE = 0.01;

   private double purchase;
   private double payment;

   /**
      Constructs a cash register with no money in it.
   */
   public CashRegister()
   {
      purchase = 0;
      payment = 0;
   }

   /**
      Records the purchase price of an item.
      @param amount the price of the purchased item
   */
   public void recordPurchase(double amount)
   {
      purchase = purchase + amount;
   }
   
   /**
      Enters the payment received from the customer.
      @param dollars the number of dollars in the payment
      @param quarters the number of quarters in the payment
      @param dimes the number of dimes in the payment
      @param nickels the number of nickels in the payment
      @param pennies the number of pennies in the payment
   */
   public void enterPayment(int dollars, int quarters, 
         int dimes, int nickels, int pennies)
   {
      payment = dollars + quarters * QUARTER_VALUE + dimes * DIME_VALUE
            + nickels * NICKEL_VALUE + pennies * PENNY_VALUE;
   }
   
   /**
      Computes the change due and resets the machine for the next customer.
      @return the change due to the customer
   */
   public double giveChange()
   {
      double change = payment - purchase;
      purchase = 0;
      payment = 0;
      return change;
   }
}

[/spoiler]

[spoiler title=’CashRegisterTester’]

/**
   This class tests the CashRegister class.
*/
public class CashRegisterTester
{
   public static void main(String[] args)
   {
      CashRegister register = new CashRegister();

      register.recordPurchase(0.75);
      register.recordPurchase(1.50);
      register.enterPayment(2, 0, 5, 0, 0);
      System.out.print("Change: ");
      System.out.println(register.giveChange());
      System.out.println("Expected: 0.25");

      register.recordPurchase(2.25);
      register.recordPurchase(19.25);
      register.enterPayment(23, 2, 0, 0, 0);
      System.out.print("Change: ");
      System.out.println(register.giveChange());
      System.out.println("Expected: 2.0");
   }
}



[/spoiler]

[spoiler title=’CashRegisterSimulator’]

import java.util.Scanner;

/**
   This program simulates a transaction in which a user pays for an item
   and receives change.
*/
public class CashRegisterSimulator
{
   public static void main(String[] args)
   {
      Scanner in = new Scanner(System.in);

      CashRegister register = new CashRegister();

      System.out.print("Enter price: ");
      double price = in.nextDouble();
      register.recordPurchase(price);

      System.out.print("Enter dollars: ");
      int dollars = in.nextInt();
      System.out.print("Enter quarters: ");
      int quarters = in.nextInt();
      System.out.print("Enter dimes: ");
      int dimes = in.nextInt();
      System.out.print("Enter nickels: ");
      int nickels = in.nextInt();
      System.out.print("Enter pennies: ");
      int pennies = in.nextInt();
      register.enterPayment(dollars, quarters, dimes, nickels, pennies);

      System.out.print("Your change: ");
      System.out.println(register.giveChange());
   }
}

[/spoiler]

OOD: My School

School Application from Ben Grass original presentation on 2/18/16

appschool

Classwork:
Period 4

a. The Student ADT:
i. init “classes” array to constant numCourses = 8
ii. create a new instance field, courseCount
Implement the following methods:
i. public void addCourse(Course aCourse):
ii. public String getAllInfo(), it should return name, age, gap, grade and a list of all classes.
iii. public String getCourses(), it returns all courses names.

c. The Course ADT:
i. Overload constructor so subject, teacher and period are the input arguments.

d. The School ADT:
i. Implement the method public String getAllStudentNames(). It should return all the students names.
ii. Implement the method public String getAllStuInfo(). It should return name, age, gap, grade and classes for all students.

  • main:
    a. Create a new class, (the driver) MySchool
    b. Copy the main method from School and remove it.
    c. Create 3 or 4 more Course objects with your own information.
    d. Create 2 or 3 more Teacher objects with your own information.
    e. Create 5 or 6 more Student objects with your own information.
    f. Add all students to PHS.
    g. Add all teachers to PHS.
    h. Add 2 courses to 4 students.
    i. Add the 4 students to a teacher.
    j. Print all students names from the teacher above.
    k. Print all PHS students names.

Period 5

Classwork:

a. The Student ADT:
i. Overload public Student(String name, int year, double GPA)
ii. Implement the method public void addCourse(Course aCourse)
iii. Implement the method public String getAllInfo() in the Student ADT. It should print name, age, gap, grade and classes for all students.

b. The Course ADT:
i. Overload the constructor so subject, teacher and period are the input arguments.

d. The Teacher ADT:
i. Add String degree instance field
ii. Overload public Teacher(String degree, String name, int experience).

c. The School ADT:
i. Implement the method public String getAllStudentNames(). It should return all the students names.

NOTE: some extra instance field are needed.

  • main:
    a. Create a new class, (the driver) MySchool
    b. Copy the main method from School and remove it.
    c. Create 3 or 4 more Course objects with your own information.
    d. Create 2 or 3 more Teacher objects with your own information.
    e. Create 5 or 6 more Student objects with your own information.
    f. Add all students to PHS.
    g. Add all teachers to PHS.
    h. Add 2 courses to 4 students.
    i. Add the 4 students to a teacher.
    j. Print all students names from the teacher above.
    k. Print all PHS students names.


Homework:

* Documentation for each method in each ADT. Include at least one comment line describing the purpose of the method.
* Make all the instance fields private.
* Implement the following methods:
getAllTeachersName()
getAllTeacherStudentNames()

OOD – Pseudocode for your NBody Simulation

Here is a general guide/pseudocode for your OOD N-Body Simulation

Planet ADT

planet
Attributes: x, y, vx, vy, m
Behaviors:
Getter methods(accessors):
one for each attribute
overload toString method

Setter methods (mutators):
one for each attribute
update method with three arguments: mass, x position and y position of another body to calculate the distance between the two bodies, the force between the two bodies, the new velocity in vx and vy components.
position method: to calculate the new x and y coordinates using the updated vx and vy with deltaT
draw method: to “draw” the image

Dynamic System ADT
dynaic sys
Attributes: Planet array

Behaviors:
motion method:
Accessor and mutator. It passes the mass, x and y positions from one body to another in the array of planets by using nested “for” loops.
draw method to show new positions

System Simulator “main”:

Set the universe scale
Create each planet and sun (as a planet)
Create array of planets
Create Dynamic System with the array of planets
Optional but pretty useful —> Threads:

while (true)
        {
            motion
            draw
            
            try { Thread.sleep(150); }
            catch (InterruptedException e) { System.out.println("Error sleeping"); }
        }

OOD Project: My Application

Programming Project: My Application

Write your own application based on a set of interacting objects.
Here are some ideas keeping in mind a simplified system and yet a good testing class. Your test class must include activities between the objects and their methods.

Requirements for the project:
1. Methods must be consistent: toSTring(), getter and setter methods.

2. Encapsulation must be enforced. All instance fields should be private.

3. Objects from different ADTs must interact with each other.

4. The test driver must execute all parts of the implementation.

Advice:

1. Keep it simple. You can add more after it runs successfully. You can keep the big picture in mind but develop from small components.

2. Start with just two ADT objects just like in My School example. First start with Student and Course objects only.


https://java.mrseliasclasses.org/my-school-how-to-implement-a-multi-adt-application-ood/

Later, we add Teacher and after that add the School ADT. Example will be provided shortly.
https://java.mrseliasclasses.org/my-school-multi-adt-application-ood-add-more/

3. The test driver should be the final version of the many changes and additions you made as you develop your full application.
In this version of your project, submit two ADTs and a test driver with minimal activity between the object(s) of each ADT.


Grade notes:
If your ADTs have only String objects and primitive data types as instance fields, the best grade you can get is a 65.

If your ADTs do not interact with each other, the best grade you can get is a 65.

If you only have 2 ADTs interacting with each other, the best grade you can get is a 80. Optimal number of interacting ADTs is 3.

1. A good description of your project – Tell the story about your application and make sure the story clearly identifies the objects you create from the different ADTs.
2. Author’s name
3. Date and java version
4. Include the output from the your test driver
5. The test driver should have enough activity to test all methods from each ADT

Cell Mitosis – OOD

What is cell mitosis? In cell biologymitosis (/maɪˈtoʊsɪs/) is a part of the cell cycle when replicated chromosomes are separated into two new nuclei. https://en.wikipedia.org/wiki/Mitosis

Write an ADT, Cell_YI with the instance fields, the attributes which identify all the different components in a cell and with the purpose of illustrating (with text only) the activity of mitosis in the driver or test class.

Remember what an abstraction is! It is a simplified version or a real thing. In your assignment, you need to simplify the process in cell mitosis and yet the general idea must not be lost. This is an open assignment that would allow you to develop your skills not just as a programmer, also as a designer.

Write the test driver, CellMitosisTest_YI.java, to simulate the mitosis of a cell. This simulation is not visual. It is text-based. Since it is text-based, be clear in your messages when describing each step of the mitosis and how it takes place. It should describe the process of cell mitosis.

Your methods, behaviors have to be clearly defined and well documented. A well-designed ADT has behaviors that return a string so printing takes place in the driver. Your output should be understood by anyone who wants to learn about Cell Mitosis in a biology class at PHS.

The images below are examples of how detail you want the abstraction can be.