Chapter 3

<< Chapter 2 | HomeworkTrailIndex | Chapter 4 >>

Demo Code: CashRegister

We always start by describing what the "black box" should do. So we first make a "tester" class that will make an instance of our yet-to-be-wriiten CashRegister. We then imagine the methods that we would like our CashRegister to have, and work out some expected results, even before we write the CashRegister class

CashRegisterTester.java

/**
   A class to test the CashRegister class.
*/
public class CashRegisterTester
{
   public static void main(String[] args)
   {
      CashRegister register = new CashRegister();
      register.recordPurchase(29.50);
      register.recordPurchase(9.25);
      register.enterPayment(50);
      double change = register.giveChange();
      System.out.println(change);      
      System.out.println("Expected: 11.25");          
   }
}

Now we have some idea for making our CashRegister class, how to make the constructor, and the methods we need:

/**
   A cash register totals up sales and computes change due.
*/
public class CashRegister
{
   /**
      Declare the CashRegister's attributes
    */
   private double total;
   private double payment;

   /**
      Constructs a cash register with no money in it.
   */
   public CashRegister()
   {

   }

   /**
      Records the sale of an item.
      @param amount the price of the item
   */
   public void recordPurchase(double amount)
   {

   }

   /**
      Enters the payment received from the customer.
      @param amount the amount of the payment
   */
   public void enterPayment(double amount)
   {

   }

   /**
      Computes the change due and resets the machine for the next customer.
      @return the change due to the customer
   */
   public double giveChange()
   {   

   }

}

Next we write the code that will make it function the way we expect. Once the basics are working we can expand our "tester" to include new features, like keeping track how much money we have in the CashRegister or perhaps having it charge a certain percentage sales tax.

Song class

I made a Tester class that will test your Song class. It should be able to keep track of the song's title, artist, rank, time, and number of plays, and it should be able to show and change any of these fields. Finally, overwrite the toString() method so we can print out all the song information

SongTester.java

import java.util.Scanner;


public class SongTester {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Song song=new Song();
		Scanner keyboard=new Scanner(System.in);
		String input="";
		while (input.indexOf("q")<0)
		{
			processCommand(keyboard, song, input);
			System.out.println("\nCurrently: "+song+"\n");
			System.out.print("Command (Title, Artist, Rank, Time, Plays, Quit): ");
			input=keyboard.nextLine();
			input=input.toLowerCase();

		}
		System.out.println("\nThanks.. we exit with the song being:\n"+song);


	}
	public static void processCommand(Scanner keyboard, Song song, String input){
		if (input.equals("title"))
		{
			System.out.print("Currently: "+song.getTitle()+"\nNew Title: ");
			song.setTitle(keyboard.nextLine());
		}
		else if (input.equals("artist"))
		{
				System.out.print("Currently: "+song.getArtist()+"\nNew artist name: ");
				song.setArtist(keyboard.nextLine());
		}
		else if (input.equals("rank"))
		{
			System.out.print("Currently: "+song.getRank()+"\nNew rank: ");
			int newRank=Integer.parseInt(keyboard.nextLine());
			song.setRank(newRank);				
		}
		else if (input.equals("time"))
		{
			System.out.print("Currently: "+song.getTime()+"\nNew time: ");
			double newTime=Double.parseDouble(keyboard.nextLine());
			song.setTime(newTime);				
		}
		else if (input.equals("plays"))
		{
			System.out.print("Currently: "+song.getPlayCount()+"\nNew number of plays: ");
			int newPlays=Integer.parseInt(keyboard.nextLine());
			song.setPlayCount(newPlays);				
		}

	}
}

Song.java

public class Song 
{
	//First declare the attributes of a Song Object:


	//Now declare your Song constructor:


	//Next declare your object's methods:
}

Make sure you know and understand the answers to the following:

  • R3.2 Explain the difference between

BankAccount b; and BankAccount b = new BankAccount(5000);

  • R3.8 What does the following method do? Give an example of how you can call the method.
public class BankAccount
{
   public void mystery(BankAccount that, double amount)
   {
      this.balance = this.balance - amount;
      that.balance = that.balance + amount;
   }
   . . . // Other bank account methods 
}

Dot Demo Click this for the Video

Review Exercises

These are important activities to do, but not really something I can grade. This is like the "Training ground" in a video game where you learn the buttons before you go out on a quest. Skip these, and you may not last very long in the game.

  • R3.10 What are the accessors and mutators of the CashRegister class?
  • R3.11 Explain the difference between a local variable and a parameter variable.

Starter Code for Homework

I made a video podcast to show you how to work with the eclipse IDE, but feel free to use BlueJ. You can copy the basic BankAccount class right here from the class wiki, then add the method addInterest() to what is already there. Feel free to retype everything from the book if you think you will learn more by carefully thinking about why the code that is there NEEDS to be there.

For the 9 point version, you need to make an Employee class, but you can just copy and paste the tester class to see if it works correctly

For the 10 point version, you need to make the Car class and the CarTester class.

BankAccount.java

/**
   A bank account has a balance that can be changed by 
   deposits and withdrawals.
*/
public class BankAccount
{  
   /**
      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)
   {  
      double newBalance = balance + amount;
      balance = newBalance;
   }

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

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

   private double balance;
}

BankAccountTester.java

/**
   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.0");      
   }
}

For 8 points:

Programming Exercise P3.2 (add the addInterest(double interest) method to the BankAccount class) The explicit parameter is the interest (for example 0.03 is three percent interest)

Here is a sample Tester class to see if your method is working properly:

/**
   A class to test the BankAccount class.
*/
public class BankAccountInterestTester
{
   /**
      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.0");
      harrysChecking.addInterest(0.03);
      System.out.println(harrysChecking.getBalance());
      System.out.println("Expected: 1545.0");
     //now a different interest, 5%
      harrysChecking.addInterest(0.05);
      System.out.println(harrysChecking.getBalance());
      System.out.println("Expected: 1622.25");
   }
}

For 9 Points:

Programming assignment P3.4 (Make a Employee class with methods getName(), getSalary() and raiseSalary(double byPercent) methods). There should be a constructor that can take a String and a double to set the name and initial salary of the employee. For example Employee president=new Employee("Fr Tony", 20.0); should make a new Employee called president whose name is "Fr Tony" and whose salary is $20. The explicit parameter byPercent of the raiseSalary method should be .1 for ten percent, 2.0 for 200%, etc.

Here is a sample EmployeeTester class to see if your Employee class is working properly:

EmployeeTester.java

public class EmployeeTester2
{
   public static void main(String[] args)
   {
       Employee president=new Employee("Fr Tony", 20.0);
       System.out.print(president.getName()+" gets $");
       System.out.println(president.getSalary() );
       System.out.println("Expected: Fr Tony gets $20.0");
       president.raiseSalary (.1); //a raise of 2 dollars, right?
       System.out.print(president.getName()+" now gets $");
       System.out.println(president.getSalary() );
       System.out.println("Expected: Fr Tony now gets $22.0");
       System.out.println(president.getSalary() );
       System.out.println("Expected: Fr Tony still gets $22.0");
       System.out.println(president.getSalary() );
       System.out.println("Expected: Fr Tony still gets $22.0");
       ///Another raise of 10%
       president.raiseSalary (.1);//a raise of 2.2 dollors, right?
       System.out.print(president.getName()+" now gets $");
       System.out.println(president.getSalary() );
       System.out.println("Expected: Fr Tony now gets $24.20");
    }  
}

For 10 Points:

Programming Exercise P3.5 (Make a Car class and a CarTester class based on the sample usage described on page 126) This is worth 10 points since you have to make your own Tester class.

Sample Usage:

Car myHybrid = new Car(50); // 50 miles per gallon
myHybrid.addGas(20); // Tank 20 gallins
myHybrid.drive(100); // Drive 100 Miles
double gasLeft = myHybrid.getGasInTank(); // get gas remaining in Tank

you may assume that the drive method is never called with a distance that consumes more than the available gas.

Supply both the Car class and the CarTester class that test all methods.

CarTester.java

public class CarTester
   {
      public static void main(String [] args)
      {
         Car myHybrid = new Car(50); // 50 miles per gallon
         myHybrid.addGas(20); //Tank is 20 gallons
         myHybrid.drive(100); // consumes 2 gallons
         double gasLeft = myHybrid.getGasInTank();
         System.out.println("Hybrid has "+myHybrid.getGasInTank()+" gallons left");
         System.out.println("Expected: 18");

         Car anotherCar = new Car(20); //Only 20 mpg for this one
         anotherCar.addGas(10);//ten galons, so it can go 200 miles, right?
         anotherCar.drive(50); // it should only go 150 more, right?
         System.out.println("Tank has "+anotherCar.getGasInTank()+" galllons left");
         System.out.println("Expected: 7.5");
       }
   }

Car.java

/**
      A car can drive and consume fuel.
   */
   public class Car
   {

      /**
         Constructs a car with a given fuel efficiency.
         @param anEfficiency the fuel efficiency of the car
      */
      public Car(double anEfficiency)
      {
         . . .
      }

      /**
         Adds gas to the tank.
         @param amount the amount of fuel to add
      */
      public void addGas(double amount)
      {
         . . .
      }

      /**
         Drives a certain amount, consuming gas.
         @param distance the distance driven
      */
      public void drive(double distance)
      {
         . . .
      }

      /**
         Gets the amount of gas left in the tank.
         @return the amount of gas
      */
      public double getGasInTank()
      {
         . . .
      }
      private double gas;
      private double efficiency;
   }

For 11 points:

Project 3.1 (Enhance the BankAccount Class to charge fees, a fixed amount of fee transactions, and a new method deductMonthlyCharge()) For ease of grading, design the BankAccount class so that you can withdraw money three times without any charge, but any more withdrawal will deduct a two dollar transaction fee from the account. The monthly charge should be set to $7.50 per month. Here is an example "tester" class. This is extra credit since you need a "if" statement to decide if a fee is charged for a withdrawal or not. If you want a hint, look at Chapter 5 section 1!

BankAccountTester11Points.java

/**
   A class to test the BankAccount class.
*/
public class BankAccountTester11Points
{
   /**
      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(50);
      harrysChecking.withdraw(150);
      harrysChecking.withdraw(100);
      System.out.println(harrysChecking.getBalance());
      System.out.println("Expected: 1700.0");    
      harrysChecking.withdraw(100);
      harrysChecking.withdraw(100);
      System.out.println("Expected: 1496.0 after extra withdrawal fees");      
      harrysChecking.deductMonthlyCharge();
     System.out.println("Expected: 1488.5 after monthly charges");      
   }
}