Author Archives: graceliana@gmail.com

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 w Animations: The Dodge

Animations using java
duke

Screen Shot 2015-02-23 at 12.19.21 AM

Look at the following programs, add them to your project, play with them and understand them. You can use them to create your Dodge Game. However, you must use ArrayLists. 

MouseFollower.java
OneSimpleAttractor.java
SimpleAttractors
Springs.java

Classwork:
The Dodge Game. Implement the game dodge using StdDraw: move a blue disc within the unit square to touch a randomly placed green disc, while avoiding the moving red discs. After each touch, add a new moving red disc.

 

 

/******************************************************************************
 *  Compilation:  javac MouseFollower.java
 *  Execution:    java MouseFollower
 *  Dependencies: StdDraw.java
 *
 *  Draw a blue filled circle wherever the mouse is, in cyan if the
 *  mouse is pressed.
 *
 *
 *  % java MouseFollower
 *
 *  Credits:  Jeff Traer-Bernstein
 *
 ******************************************************************************/


public class MouseFollower {
    public static void main(String[] args) {

        StdDraw.enableDoubleBuffering();

        while (true) {

            // mouse click
            if (StdDraw.isMousePressed()) StdDraw.setPenColor(StdDraw.CYAN);
            else                          StdDraw.setPenColor(StdDraw.BLUE);

            // mouse location
            StdDraw.clear();
            double x = StdDraw.mouseX();
            double y = StdDraw.mouseY();
            StdDraw.filledCircle(x, y, 0.05);
            StdDraw.show();
            StdDraw.pause(10);
        }
    }
}


//Copyright © 2000–2017, Robert Sedgewick and Kevin Wayne. 
//Last updated: Fri Oct 20 14:12:12 EDT 2017.

/******************************************************************************
 *  Compilation:  javac OneSimpleAttractor.java
 *  Execution:    java OneSimpleAttractor
 *  Dependencies: StdDraw.java
 *
 *  A particle is attracted to the current location of the mouse.
 *  Incorporates drag.
 *
 *  
 *  % java OneSimpleAttractor
 *
 *
 *  Credits:  Jeff Traer-Bernstein
 *
 ******************************************************************************/



public class OneSimpleAttractor {
    public static void main(String[] args) {
        double rx = 0.0, ry = 0.0;   // position
        double vx = 0.0, vy = 0.0;   // velocity
        double mass = 1.0;           // mass
        double dt   = 0.5;           // time quantum
        double drag = 0.1;           // mess around with this a bit
        double attractionStrength = 0.01;
        
        // do the animation
        StdDraw.enableDoubleBuffering();
        while (true) {

            // compute the attractive force to the mouse, accounting for drag
            double dx = StdDraw.mouseX() - rx;
            double dy = StdDraw.mouseY() - ry;
            double fx = (dx * attractionStrength) - (drag * vx);
            double fy = (dy * attractionStrength) - (drag * vy);
    
            // Euler step: update velocity, then position
            vx += fx * dt / mass;
            vy += fy * dt / mass;
            rx += vx * dt;
            ry += vy * dt;
            
            // draw particle
            StdDraw.clear();
            StdDraw.setPenColor(StdDraw.BLUE);
            StdDraw.filledCircle(rx, ry, 0.02);
            StdDraw.show();
            StdDraw.pause(10);
        }
    }
}


Copyright © 2000–2017, Robert Sedgewick and Kevin Wayne. 
Last updated: Fri Oct 20 14:12:12 EDT 2017.

/******************************************************************************
 *  Compilation:  javac SimpleAttractors.java
 *  Execution:    java SimpleAttractors n
 *  Dependencies: StdDraw.java
 *
 *  n particles are attracted to the mouse; randomly rearrange when
 *  user clicks.
 *
 *  % java SimpleAttractors 20
 *
 *  Credits:  Jeff Traer-Bernstein
 * 
 ******************************************************************************/
public class SimpleAttractors {
    public static void main(String[] args) {
        int n = Integer.parseInt(args[0]);
        double[] rx = new double[n];
        double[] ry = new double[n];
        double[] vx = new double[n];
        double[] vy = new double[n];
        double dt = 0.5;
        double mass = 1.0;
        double drag = 0.05;     // try changing this to 0.1 or 0.01 or even 0...
        double attractionStrength = 0.01;
        
        // initialize the drawing area
        StdDraw.setPenColor(StdDraw.BLUE);
        StdDraw.enableDoubleBuffering();
        StdDraw.setScale(-1, +1);
        // do the animation
        while (true) {
            // if the mouse is pressed add some random velocity to all the particles
            if (StdDraw.isMousePressed()) {
                for (int i = 0; i < n; i++) {
                    vx[i] = 0.2 * Math.random() - 0.1;
                    vy[i] = 0.2 * Math.random() - 0.1;
                }
            }
            
            // clear all the forces
            double[] fx = new double[n];
            double[] fy = new double[n];
            
            // add attraction forces for attraction to the mouse
            for (int i = 0; i < n; i++) {
                double dx = StdDraw.mouseX() - rx[i];
                double dy = StdDraw.mouseY() - ry[i];
                fx[i] += attractionStrength * dx;
                fy[i] += attractionStrength * dy;
            }
            
            // add drag forces to all particles
            // drag is proportional to velocity in the opposite direction
            for (int i = 0; i < n; i++) {
                fx[i] += -drag * vx[i];
                fy[i] += -drag * vy[i];
            }
            
            // update positions
            // euler step
            for (int i = 0; i < n; i++) {
                vx[i] += fx[i] * dt / mass;
                vy[i] += fy[i] * dt / mass;
                rx[i] += vx[i] * dt;
                ry[i] += vy[i] * dt;
            }
            
            
            StdDraw.clear();
            
            // draw a filled circle for each particle
            for (int i = 0; i < n; i++) {
                StdDraw.filledCircle(rx[i], ry[i], 0.01);
            }
            
            StdDraw.show();
            StdDraw.pause(10);
        }
    }
}
/******************************************************************************
 *  Compilation:  javac Springs.java
 *  Execution:    java Springs N
 *  Dependencies: StdDraw.java
 *
 *  Simulates a system of springs.
 *
 *  % java Springs 15
 *
 *  Credits:  Jeff Traer-Bernstein
 *
 ******************************************************************************/
public class Springs {
    public static void main(String[] args) {
        // mess around with this, try 7, 8, 9, 10, 11, 12, 15
        // probably have to turn down the spring force to keep it stable after that...
        int n = Integer.parseInt(args[0]);
        double[] rx = new double[n];
        double[] ry = new double[n];
        double[] vy = new double[n];
        double[] vx = new double[n];
        double particleMass = 1.0;
        double drag = 0.1;
        double springStrength = 0.1;
        double springLength = 30;
        double gravity = 1.0;
        double timeStep = 0.5;
        
        // set up the drawing area
        StdDraw.setXscale(0, 100);
        StdDraw.setYscale(0, 100);
        StdDraw.setPenColor(StdDraw.BLUE);
        StdDraw.setPenRadius(0.0025);
        StdDraw.enableDoubleBuffering();
        
        // initialize the particle positions randomly
        for (int i = 0; i < n; i++) {
            rx[i] = 100 * Math.random();
            ry[i] = 100 * Math.random();
        }
        
        
        // do the animation
        while (true) {
            // clear all the forces
            double[] fx = new double[n];
            double[] fy = new double[n];
            
            // spring forces act between every pairing of particles
            // spring force is proportional to the difference between the rest length of the spring
            // and the distance between the 2 particles it's acting on
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < n; j++) {
                    if (i == j) continue;
                    // calculate distance between particles i and j
                    double dx = rx[j] - rx[i];
                    double dy = ry[j] - ry[i];
                    double length = Math.sqrt(dx*dx + dy*dy);
                    
                    // figure out the force
                    double force = springStrength * (length - springLength);
                    double springForceX = force * dx / length;
                    double springForceY = force * dy / length;
                    
                    // update the force
                    fx[i] += springForceX;
                    fy[i] += springForceY;
                }
            }
            
            // add drag force
            // drag is proportional to velocity but in the opposite direction
            for (int i = 0; i < n; i++) {
                fx[i] += -drag * vx[i];
                fy[i] += -drag * vy[i];
            }
            
            // add gravity forces
            // just add some force pointing down to all of them
            for (int i = 0; i < n; i++) {
                fy[i] += -gravity;
            }
            
            // fix particle 1 at the mouse position
            rx[0] = StdDraw.mouseX();
            ry[0] = StdDraw.mouseY();
            vx[0] = 0.0;
            vy[0] = 0.0;
            fx[0] = 0.0;
            fy[0] = 0.0;
            
            // update positions using approximation
            for (int i = 0; i < n; i++) {
                vx[i] += fx[i] * timeStep/particleMass;
                vy[i] += fy[i] * timeStep/particleMass;
                rx[i] += vx[i] * timeStep;
                ry[i] += vy[i] * timeStep;
            }
            
            
            // clear
            StdDraw.clear();
            
            // draw everything
            for (int i = 0; i < n; i++) {
                // draw a circle for each node
                StdDraw.filledCircle(rx[i], ry[i], 1.0);
                
                // draw the connections between every 2 nodes
                for (int j = 0; j < i; j++) {
                    StdDraw.line(rx[i], ry[i], rx[j], ry[j]);
                }
            }
            
            // show and wait
            StdDraw.show();
            StdDraw.pause(10);
        }
    }
}
Copyright © 2000–2017, Robert Sedgewick and Kevin Wayne. 
Last updated: Fri Oct 20 14:12:12 EDT 2017.

If you are missing isMousePressed in any of your programs, you should copy the StdDraw below to your original. StdDraw Code

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: Object Oriented Design Revisited – Charge ADT

Screen Shot 2015-05-01 at 11.18.58 AM

In.java

Screen Shot 2015-04-29 at 10.32.07 AM

Object Oriented Design Revisited

/*************************************************************************
 *  Compilation:  javac Charge.java
 *  Execution:    java Charge x y
 *
 *************************************************************************/

public class Charge {
    private double rx, ry;   // position
    private double q;        // charge

    public Charge(double x0, double y0, double q0) {
        rx = x0;
        ry = y0;
        q  = q0;
    }

    public double potentialAt(double x, double y) {
        double k = 8.99e09;
        double dx = x - rx;
        double dy = y - ry;
        return k * q / Math.sqrt(dx*dx + dy*dy);
    }

    public String toString() {
        return q + " at " + "(" + rx + ", " + ry + ")";
    }

    public static void main(String[] args) {
        double x = Double.parseDouble(args[0]);
        double y = Double.parseDouble(args[1]);
        Charge c1 = new Charge(.51, .63, 21.3);
        Charge c2 = new Charge(.13, .94, 81.9);
        System.out.println(c1);
        System.out.println(c2);
        double v1 = c1.potentialAt(x, y);
        double v2 = c2.potentialAt(x, y);
        StdOut.println(v1+v2);
    }
}


Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne. 
Last updated: Wed Feb 9 09:07:43 EST 2011.

Basic elements of a data type.

  • API.
  • Class.
  • Access modifiers.
  • Instance variables.
  • Constructors.
  • Instance methods.
  • Variable names in methods.

Basic components that you need to understand to be able to build data types in Java.

classcharge

NOTE:

You should be working on the programming assignment and gradient assignments before you start working on OOD programs.

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"); }
        }