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.
- CashRegisterTest.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"); } }
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.1664642257.txt.gz · Last modified: 2022/10/01 12:37 by frchris