writing_classes_practice
This is an old revision of the document!
Table of Contents
Writing Classes Practice
Cash Register
Use the following tester class to figure out how to make your own CashRegister.java
class file.
Hints:
- You probably need to keep track of the total of the purchase, and how much the customer has already paid,
- You need a constructor to initialize the fields.
- You need a
recordPurchase
method that added to the amount the customer owes - You need an
enterPayment
method that records how much the customer has paid - You need a method
giveChange
, that return the change and adjusts the amount due and clears the amount the custumer.
- CashRegisterTest.java
/** A class to test the CashRegister class. */ public class CashRegisterTester { has paid 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"); } }
Song
- 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); } } }
writing_classes_practice.1664642801.txt.gz · Last modified: 2022/10/01 12:46 by frchris