Category Archives: Lesson

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 – My School: Multi – ADT application – Start Small

 /**
 * Course: ADT for students' courses.
 * MySchool Application
 *  The Course ADT:
 *  Overload constructor so subject, teacher and period are the input 
 *    arguments.
 *
 * @RA & mrs.e
 * @1.8 3/13/2018 & 5/10/19
 */
public class Course
{
    private String name;
    private String period; 
    private String roomNumber;
    public Course(String name, String period, String roomNumber)
    {
        this.name = name;
        this.period=period;
        this.roomNumber = roomNumber;
    }

    /**
     * parm name - this is the name of the course 
     */
    public String getName()
    {
        return name + " ";
    }

    // draw course(s)
    public void draw()
    {
        StdDraw.picture(1.5, -1.5, "school_courses.png",1.5,1.5);
    }

    /**
     * this is the period of the class 
     */
    public String getPeriod()
    {
        return period + " ";
    }

    /**
     * this is the room no of the class 
     */
    public String getRoomNumber()
    {
        return roomNumber + " ";
    }
    
    public String toString()
    {
        String output = "Class name: " + name + "\nRoom Number: "  
                    + roomNumber + "\nPeriod:  " + period;
                    
        return output;
    }
}




/**
 * This is an ADT to represent an abstraction of a student 
 * Student s1 = new Student("Bob", "Smith", 15, "male", 1234);//constructor  
 * @Rida Ahmed & mrs.e
 * @1.8 3/13/2018 & 5/10/19
 */
public class Student
{
    private String firstName;
    private String lastName;
    private String age;
    private String gender;
    private String id;
    private Course [] myCourses = new Course [3]; //ADT as an instance field 

    // constructor
    public Student (String firstName,String lastName,String age,String gender,String id)
    {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
        this.gender = gender;
        this.id = id; // on hold, not being used  
    }

    // draw method
    public void draw()
        {
        StdDraw.picture(0.4, 0.5, "school_happykids.png",3.7,2);
  
        }

    // getter methods
    public String getName ()
    {
        return firstName + " " + lastName;
    }

    public String getPersonalInfo () 
    {
       return age + ", " + gender + ", " + id; 
       
    }

    // setter methods
    public void setCourses(Course [] courses) 
    {
        for(int i = 0; i < courses.length; i++){
            myCourses[i]=courses[i];
        }
    }
    public void setACourse (Course aCourse){
        //interesting 
    }
    

    // overridden method
    public String toString()
    {
        String output = "";
        output += "Student name: " + firstName + " " + lastName + "\nCourses: " ;

        for (int i = 0; i < myCourses.length ; i++) 
        {
            output += "\n\n" + myCourses[i];
        }
        
        return output;
    }
}

/**
 * Customized driver to test all the different parts of my class MySchoolTest: student(s)
 *
 * @RA & mrs.e
 * @1.8 3/13/18 & 5/10/19
 */
public class MySchoolTest
{
    public static void main(String [] args)
    {
        // set canvas scales
        StdDraw.setXscale(-2,2);
        StdDraw.setYscale(-2,2);

        //create an object of student
        //then create 3 objects of course
        //afterwards we add the 3 objects of course to the student 
        Student konoa = new Student("Konoa", "Smith", "15", "female", "1234");  

        Course c1 = new Course("Biology", "5", "102");
        Course c2 = new Course("precalculus", "4", "136");
        Course c3 = new Course("APUSH", "7", "117");

        // print a course information
        System.out.println("Print a course ");
        System.out.println(c1);

        // add all courses to an array
        Course [] courses = { c1,c2,c3};

        // assign all courses to a student
        konoa.setCourses(courses);

        //print a student info and courses
        System.out.println("\n" + konoa);

        // draw a student and friends
        konoa.draw()

    
   }

}

/* 
 * Print a course 
 * Class name: Biology
 * Room Number: 102
 * Period:  5

 * Student name: Konoa Smith
 * Courses: 

 * Class name: Biology
 * Room Number: 102
 * Period:  5

 * Class name: precalculus
 * Room Number: 136
 * Period:  4

 * Class name: APUSH
 * Room Number: 117
 * Period:  7

 * 
 */
Konoa and friends
/**
 * Customized driver to test all the different parts of my class MySchoolTest: course(s)
 *
 * @RA & mrs.e
 * @1.8 3/13/18 & 5/10/19
 */
public class MySchoolTest
{
    public static void main(String [] args)
    {
        // set canvas scales
        StdDraw.setXscale(-2,2);
        StdDraw.setYscale(-2,2);

        //create an object of student
        //then create 3 objects of course
        //afterwards we add the 3 objects of course to the student 
        Student konoa = new Student("Konoa", "Smith", "15", "female", "1234");  

        Course c1 = new Course("Biology", "5", "102");
        Course c2 = new Course("precalculus", "4", "136");
        Course c3 = new Course("APUSH", "7", "117");

        // print a course information
        System.out.println("Print a course ");
        System.out.println(c1);

        // add all courses to an array
        Course [] courses = { c1,c2,c3};

        // assign all courses to a student
        konoa.setCourses(courses);

        c1.draw();
    
   }

}

OOD NBody Simulation Computations

Some extra help

planetarysys

Calculate for each body in the system and every other body:

  • distance square = (x distance between itself and the other body)^2 + (y distance between itself and the other body)^2
  • force = G * its mass * the other’s mass / distance^2
  • forceX = force * (the other’s x position – its x position )/ distance
  • forceY = force * (the other’s y position – its y position )/ distance
  • accelerationX = forceX / its mass
  • accelerationY = forceY / its mass
  • velocityX += deltaT * accelerationX
  • velocityY += deltaT * accelerationY

 

update the new position for the body

  • x position += deltaT * velocityX
  • y position += deltaT * velocityY

OOD: Advanced topic: The “this” operator

Designing classes
The this operator
Make sure you read thoroughly.
1. Make the following changes to the BankAccount class:
a. Include a print statement in the getBalance() method to show the reference to the implicit parameter. Include “from method getBalance”
b. Include a print statement in both constructors, “from method default constructor” and “from constructor with parameter”.
2. Implement a test class, ThisOperatorTest. In this test, create an object of the class BankAccount and print it.
3. Include a commented paragraph at the end of the test class making a conclusion on the output. Make sure you explain what the this operator does in the two programs and compare them.
4. The following questions refer to calling by reference, by value and side effects:

• Modify your BankAccount class to include a new method, transfer. This method has two input parameters, double amount and double otherBalance from a different BankAccount object. The method takes money from the calling object’s balance and increases the balance from the other object by the “amount” value. The method also includes two print statements to display each object.

System.out.println(“From transfer( ), current object @: ” + _missing parameter);
System.out.println(“From transfer( ), otherAccount @: ” + otherBalance);

Create a test class, BankAccountTest1. In main:
• Create two BankAccount objects.
• Display the balance from both objects.
• Call the transfer method from one object to transfer money to the other object’s balance.
• Display both accounts’ balance.

A different approach to the same idea in 4:
• Modify your BankAccount class to include a new method, transfer. This method has two input parameters, double amount and BankAccount otherAccount. The method takes money from the calling object’s balance and increases the otherAccount’s balance by the “amount” value. The method also includes two print statements to display each object.

System.out.println(“From transfer( ), current object @: ” + _missing parameter);
System.out.println(“From transfer( ), otherAccount @: ” + otherAccount);

Look at edmodo.com for the different posts and due dates.

OOD Project: gpa calculator

Classwork:
Write a program, YI_GPACalculator.java to read grades from a text file. The grades will have a specific structure so the marking periods, the subjects, and categories can be identified.

The file structure given here is just an example. You should notice it has some redundancy. You can configure your own structure to enable easier implementation.

[spoiler title=’gpadata.txt’]
Q1
Subject: English
Categories start:
Homework: .30
Classwork: .30
Test: .40
Categories end
Data:
Homework:
75
90
85
Classwork:
65
75
78
Test:
100
98
99
Subject: Math
Categories start:
Homework: .25
Classwork: .25
Test: .50
Categories end
Data:
Homework:
86
88
100
Classwork:
60
70
80
Test:
100
90
91
Q1 end
Q2
Subject: English
Categories start:
Homework: .30
Classwork: .30
Test: .40
Categories end
Data:
Homework:
95
80
81
Classwork:
55
95
88
Test:
93
100
85
Subject: Math
Categories start:
Homework: .25
Classwork: .25
Test: .50
Categories end:
Homework:
86
88
100
Classwork:
60
70
80
Test:
87
96
81
Q2 end
[/spoiler]

Here is some code that might help you read the file.

  1. Using PU libraries: StdIn.java
/**
 * Calculate the GPA given a file with all the requirements.
 * Q1
 * Subject: English
 * Categories start:
 * Homework: .30
 * Classwork:
 * ....
 * ....
 * END
 * 
 * java GPACalculator1 < gpadata.txt
 * 
 */
public class GPACalculator1
{
    public static void main(String [] args)
    {

            while (StdIn.hasNextLine()) {
                String s1 = StdIn.readLine();
                System.out.println(s1);
            }
          
    
    }
    
}

  1. Using java libraries:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
/**
 * Calculate the GPA given a file with all the requirements.
 * Subject: English
 * Catgories beginning:
 * 
 */
public class GPACalculator2
{
    public static void main(String [] args)
    {
        
        File file = new File(args[0]);
    
        try {
    
            Scanner sc = new Scanner(file);
    
            while (sc.hasNextLine()) {
                String s1 = sc.nextLine();
                System.out.println(s1);
            }
            sc.close();
        } 
        catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    
    }
    
}

Before you get started writing code,
1. Draft a flowchart or a concise pseudocode.
2. Trace few grades from one subject for Q1 and Q2.
3. Manually calculate the GPA for the data used in the trace.
4. Confirm that your trace and calculation coincide.

Submit all your work to edmodo.com.

OOD: ArrayList – Intro

/**
 * Test of ArrayLists basic instructions
 * 
 * @ge
 * @4/16/18
 */
import java.util.ArrayList;

public class ArrayListTest
{
   public static void main(String [] args)
   {
        
       ArrayList myList = new ArrayList();
       //ArrayList myList = new ArrayList(); // more efficient - eliminates warning
       Integer x = new Integer(45); // creates Integer 45
       
       myList.add(x); // adds Integer 45 to myList
       myList.remove(x); // removes the value 45 from myList
       x = new Integer(100); // creates Integer 100 
       myList.add(0,x); // adds Integer 100 to the beginning of myList

       System.out.println(myList.get(0)); // print the first element 
       System.out.println(myList.size()); // print the number of elements
       
       // One step further
       myList.add(5);
       myList.add(-27);
       myList.add(55);
       myList.add(0,3);
   }
}

Classwork:

Let’s use the following documentation Java™ Platform, Standard Edition 8
API Specification to create our own resources: 

ArrayList

From the documentation copy and paste the following methods’ description:

* 1
* boolean add(E e)
*
* 2
* void add(int index, E element)

* Having two methods with the same name but different argument list
* is called OVERLOADING
*
* 3
* E get(int index)
*
* 4
* E set(int index, E element)
*
* 5
* int indexOf(Object o)
*
* 6
* boolean isEmpty()
* Returns true if this list contains no elements.
*
* 7
* E remove(int index)
*
* 8
* boolean remove(Object o)
*
* 9
* int size()

Resource:
Screen Shot 2016-01-15 at 7.46.11 AM

Assignment:
ArrayListBasics_YI.java
Write a program that does the following:
Choose a meaningful and complete message for each item in the list.

  1. It creates an ArrayList, anAList of 100 random integers between any values from 1 to 1000 and find the two consecutive integers with the smallest difference between the two of them.

  2. It finds and prints with a message the largest value in anAList.

  3. It finds and prints with a message the average value in anAList.

  4. It prints all the numbers from anAList separated with a space and in one line.

  5. It prints the numbers from anAlist separated by 3 spaces in 10 columns by 10 rows format. Use printf to achieve this format. Do not use tab: “\t”.

  6. Prompt the user for an integer and replace the 10th Integer with this new one. Display a message to acknowledge wether it was found.

  7. Prompt the user for a number and search for that number. Display the number and the index where it was found.

  8. Remove 10th Integer and print a message with the number.

  9. Print the number of elements the ArrayList anAlist contains.

Note: Use printf to keep all your numbers tab properly.

/**** Make sure your documentation includes the output ****/