Category Archives: Homework

OOD: BankAccount

/**
   A bank account has a balance that can be changed by 
   deposits and withdrawals.
*/
public class BankAccount
{  
   private double balance;

   /**
      Constructs a bank account with a zero balance.
   */
   public BankAccount()
   {   
      balance = 0;
   }

   /**
      Constructs a bank account with a given balance.
      @param initialBalance the initial balance
   */
   public BankAccount(double initialBalance)
   {   
      balance = initialBalance;
   }

   /**
      Deposits money into the bank account.
      @param amount the amount to deposit
   */
   public void deposit(double amount)
   {  
      balance = balance + amount;
   }

   /**
      Withdraws money from the bank account.
      @param amount the amount to withdraw
   */
   public void withdraw(double amount)
   {   
      balance = balance - amount;
   }

   /**
      Gets the current balance of the bank account.
      @return the current balance
   */
   public double getBalance()
   {   
      return balance;
   }
}

/**
   A class to test the BankAccount class.
*/
public class BankAccountTester
{
   /**
      Tests the methods of the BankAccount class.
      @param args not used
   */
   public static void main(String[] args)
   {
      BankAccount harrysChecking = new BankAccount();
      harrysChecking.deposit(2000);
      harrysChecking.withdraw(500);
      System.out.println(harrysChecking.getBalance());
      System.out.println("Expected: 1500");      
   }
}

Classwork:

  1. Add a method sayGoodbye to the Greeter class.

  2. Add a method refuseHelp to the Greeter class. It should return a string such as “I am sorry, Dave. I am afraid I can’t do that.”

  3. Write a program that constructs a bank account, deposits $1000, withdraws $500, withdraws another $400, and then prints the remaining balance.

  4. Add a method

void addInterest(double rate)

to the BankAccount class that adds interest at the given rate. For example, after the statemetns

BankAccount momsSavings = new BankAccount(1000);
momsSavings.addInterest(10); // 10% interest

the balance in momsSavings is $1,100.

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 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

OOD: Shannon Entropy

Classwork/Homework:

These assignments are to be developed using the basic elements of object oriented design.

Generating cryptograms. A cryptogram is obtained by scrambling English text by replacing each letter with another letter. Write a program, YI_Crypto1.java to generate a random permutation of the 26 letters and use this to map letters. Give example: Don’t scramble punctuation or whitespace.

crypto

Entropy. The Shannon entropy measures the information content of an input string and plays a cornerstone role in information theory and data compression.

Screen Shot 2015-05-05 at 8.21.45 PM            Shannon Entropy Calculator

Shannon is famous for having founded information theory.
It was proposed by Claude Shannon in 1948, borrowing upon the concept in statistical thermodynamics. Assuming each character i appears with probability p(_{i}), the entropy is defined to be H = – sum p(_{i}) log(_{2})p(_{i}), where the contribution is 0 if p(_{i}) = 0. Compute entropy of DNA sequence.

(a) Write a program, YI_Entropy1.java to read in a ASCII text string from standard input, count the number of times each ASCII character occurs, and compute the entropy, assuming each character appears with the given probabilities.

(b) Repeat part (a) but use Unicode.

entropy1

Screen Shot 2015-05-25 at 1.40.56 AM

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.