/* Course: CS-182 Project: Programming 4 Name: Zaddie Arnold Date: 11/11/2015 De
ID: 3763179 • Letter: #
Question
/*
Course: CS-182
Project: Programming 4
Name: Zaddie Arnold
Date: 11/11/2015
Description: Write a program using the proper implementation of inheritance;
utilizing abstract and derived classes. Develop the DessertShop
application with the instructions provided by the assignment tasks.
*/
package dessertshop;
import java.text.NumberFormat;
/**
Module: CS-182 Introduction to Java Programming
Description: A Java program that uses the proper implementation of inheritance;
* utilizing abstract and derived classes
Input: No input. Contains abstract classes, derived classes, methods,
* constructors, etc.
Output: A receipt of the calculated prices, items, and base price.
*/
abstract class DessertItem { //abstract superclass where types of DessertItem will be derived
protected String name; //Instance variable name of item String
NumberFormat currency = NumberFormat.getCurrencyInstance(); //Formats numbers to a currency format to the nearest cent
public DessertItem () //default constructor DessertItem()
{
this.name = "";
}
public DessertItem ( String itemName ) //constructor to pass in the name of the item
{
this.name = itemName;
}
/*
Method : getName()
Parameters : void
Returns : String
Description : Returns the current name of the item
*/
public String getName ()
{
return name;
}
/*
Method : setName()
Parameters : String - Name of the item
Returns : void
Description : Sets the name instance variable
*/
public void setName ( String name )
{
this.name = name;
}
/*
Method : getCost()
Parameters : abstractdouble
Returns : void
Description : Gets the cost of the item. Undefined because each item cost is different.
*/
public abstract double getCost ();
/*
Method : toString()
Parameters : void
Returns : String
Description : Creates a String, returning the name of the item
*/
public String toString()
{
return name;
}
}
class Candy extends DessertItem { //Candy class derived from DessertItem class
double weight;
double pricePerPound;
double candyTotal;
public Candy ( String name, double weight, double pricePerPound )
{
super( name ); //calls name from superclass
this.weight = weight;
this.pricePerPound = pricePerPound;
}
@Override
/*
Method : getCost()
Parameters : void
Returns : double
Description : Calculate cost of Candy
*/
public double getCost ()
{
this.candyTotal = this.weight*this.pricePerPound;
return this.candyTotal;
}
/*
Method : toString()
Parameters : void
Returns : String
Description : Creates a String, returning Peanut Butter Fudge, weight, price, and calculated total of the item. Uses derived getCost() of superclass
*/
public String toString()
{
return name + " " + currency.format(this.getCost()) + " "
+ this.weight + " lbs @ " + currency.format(this.pricePerPound);
}
}
class Cookie extends DessertItem { //Cookie class derived from DessertItem class
int number;
double pricePerDozen;
double cookieTotal;
Cookie ( String name, int number, double pricePerDozen )
{
super( name ); //calls name from superclass
this.number = number;
this.pricePerDozen = pricePerDozen;
}
@Override
/*
Method : getCost()
Parameters : void
Returns : double
Description : Calculate cost of Cookie
*/
public double getCost ()
{ this.cookieTotal = (this.number*this.pricePerDozen)/12;
return this.cookieTotal;
}
/*
Method : toString()
Parameters : void
Returns : String
Description : Creates a String, returning Oatmeal Raisin Cookies, number, price, and calculated total of the item. Uses derived getCost() of superclass
*/
public String toString()
{
return name + " " + currency.format(this.getCost()) + " "
+ this.number + " cookies @ " + currency.format(this.pricePerDozen) + " per Dozen";
}
}
class IceCream extends DessertItem { //IceCream class derived from DessertItem class
double cost;
IceCream ( String name, double cost )
{
super( name ); //calls name from superclass
this.cost = cost;
}
@Override
/*
Method : getCost()
Parameters : void
Returns : double
Description : Calculate cost of IceCream
*/
public double getCost ()
{
return this.cost;
}
/*
Method : toString()
Parameters : void
Returns : String
Description : Creates a String, returning Vanilla Ice Cream and cost of item. Uses derived getCost() of superclass
*/
public String toString()
{
return name + " " + currency.format(this.getCost());
}
}
class Sundae extends IceCream { //Sundae class derived from DessertItem class
String toppingName;
double toppingCost;
double sundaeTotal;
Sundae ( String name, double cost, String toppingName, double toppingCost )
{
super( name, cost ); //calls name from superclass and cost from IceCream
this.toppingName = toppingName;
this.toppingCost = toppingCost;
}
@Override
/*
Method : getCost()
Parameters : void
Returns : double
Description : Calculate cost of Sundae
*/
public double getCost ()
{
this.sundaeTotal = this.cost + this.toppingCost;
return this.sundaeTotal;
}
/*
Method : toString()
Parameters : void
Returns : String
Description : Creates a String, returning Chocolate Chip Ice Cream, Fudge and cost of each. Uses derived getCost() of superclass
*/
public String toString()
{
return name + " " + currency.format(this.getCost()) + " " + this.toppingName
+ " @ " + currency.format(this.toppingCost);
}
}
public class DessertShop { //Test harness provided by instructor
public static void main ( String[] args )
{
Candy item1 = new Candy( "Peanut Butter Fudge", 2.25, 3.99 );
Cookie item2 = new Cookie( "Oatmeal Raisin Cookies", 4, 3.99 );
IceCream item3 = new IceCream( "Vanilla Ice Cream", 1.05 );
Sundae item4 = new Sundae( "Chocolate Chip Ice Cream", 1.45, "Hot Fudge", 0.50 );
System.out.println( item1 );
System.out.println( item2 );
System.out.println( item3 );
System.out.println( item4 );
}
}
The programmer will use and extend the classes and methods developed in Homework #7 to develop a Cash Register type of application. This application will declare an enumerated type ‘DessertType’, which will be used in a switch statement to determine which action needs to be taken.
Depending on the DessertType, the program should prompt for specific details in order to calculate the price for each item.
CANDY
Prompt for Name, Number of Pounds, Price per Pound
COOKIE
Prompt for Name, Number of Cookies, Price per Dozen
ICE CREAM
Prompt for Name, Number of Scoops, Price per Scoop
SUNDAE
Prompt for Name, Number of Scoops, Price per Scoop, Number of Toppings, Name of Toppings and Price per Topping
This will require a loop to Prompt for each Topping based on “Number of Toppings”
The application should be called ‘DessertShop’, which will prompt the user for items to purchase. This application will prompt the user for the name of the product. If no name is entered, the application will calculate the total cost of items entered.
The application will define four arrays for each DessertItem, which can store up to 10 items each.
Each derived class will contain a static variable which will store the total DessertItem cost and total DessertItem tax (if applicable) for that specific DessertType. The CANDY and COOKIE dessert types are taxable at 7%. The ICE CREAM and SUNDAY dessert types are non-taxable.
The DessertItem superclass will also contain a total cost and total tax static variable that will be shared between all items that were derived from that superclass.
Upon successfully entering an item, the total cost and total tax of that DessertItem will be updated, along with the total cost and total tax for all items. The application should check an item to determine if that item has already been entered, except for Sundae’s. If the item has already been entered, the existing information should be updated to include the new items.
Upon entering all items, the application should print out a summary of the DessertItem’s, along with the count, the cost and tax. (See Sample Output)
CANDY [2] Cost: $4.52 Tax: $0.32
COOKIES [24] Cost: $12.96 Tax: $0.91
ICE CREAM [1] Cost: $3.99
SUNDAE [4] Cost: $8.87
---- -------- -----
Subtotals [31] $30.34 $1.23
========
Total $31.57
HOMEWORK 7
Explanation / Answer
public abstract class DessertItem
{
protected String name;
public DessertItem()
{
this("");
}
public DessertItem(String name)
{
if (name.length() <= DessertShoppe.MAX_ITEM_NAME_SIZE)
this.name = name;
else
this.name = name.substring(0,DessertShoppe.MAX_ITEM_NAME_SIZE);
}
public final String getName()
{
return name;
}
public abstract int getCost();
}
public class DessertShoppe
{
public final static double TAX_RATE = 6.5; // 6.5%
public final static String STORE_NAME = "M & M Dessert Shoppe";
public final static int MAX_ITEM_NAME_SIZE = 25;
public final static int COST_WIDTH = 6;
public static String cents2dollarsAndCents(int cents)
{
String s = "";
if (cents < 0)
{
s += "-";
cents *= -1;
}
int dollars = cents/100;
cents = cents % 100;
if (dollars > 0)
s += dollars;
s +=".";
if (cents < 10)
s += "0";
s += cents;
return s;
}
}
public class TestCheckout
{
public static void main(String[] args)
{
Checkout checkout = new Checkout();
checkout.enterItem(new Candy("Peanut Butter Fudge", 2.25, 399));
checkout.enterItem(new IceCream("Vanilla Ice Cream",105));
checkout.enterItem(new Sundae("Choc. Chip Ice Cream",145, "Hot Fudge", 50));
checkout.enterItem(new Cookie("Oatmeal Raisin Cookies", 4, 399));
System.out.println(" Number of items: " + checkout.numberOfItems() + " ");
System.out.println(" Total cost: " + checkout.totalCost() + " ");
System.out.println(" Total tax: " + checkout.totalTax() + " ");
System.out.println(" Cost + Tax: " + (checkout.totalCost() + checkout.totalTax()) + " ");
System.out.println(checkout);
checkout.clear();
checkout.enterItem(new IceCream("Strawberry Ice Cream",145));
checkout.enterItem(new Sundae("Vanilla Ice Cream",105, "Caramel", 50));
checkout.enterItem(new Candy("Gummy Worms", 1.33, 89));
checkout.enterItem(new Cookie("Chocolate Chip Cookies", 4, 399));
checkout.enterItem(new Candy("Salt Water Taffy", 1.5, 209));
checkout.enterItem(new Candy("Candy Corn",3.0, 109));
System.out.println(" Number of items: " + checkout.numberOfItems() + " ");
System.out.println(" Total cost: " + checkout.totalCost() + " ");
System.out.println(" Total tax: " + checkout.totalTax() + " ");
System.out.println(" Cost + Tax: " + (checkout.totalCost() + checkout.totalTax()) + " ");
System.out.println(checkout);
}
}
public class CheckoutGUI extends JFrame implements ActionListener
{
private Checkout checkout= new Checkout();
private final static int INFO_SIZE = 30;
private JTextField _info = new JTextField("Number of Items: 0",100);
private String bnames[]={ "Ice Cream", "Candy", "Cookies", "Sundae"};
private String lnames[] =
{
"Name", "Price", "Weight", "Price/lbs", "Price/doz", "Number", "Topping",
"Topping Cost"
};
private String bnames2[]={"Enter", "Total"};
private String mnames[]={"Reset", "Exit"};
private JButton buttons[];
private JLabel labels[];
private JButton buttons2[];
private JTextField tfields[];
private JMenuItem menuitems[];
private JMenuBar bar = new JMenuBar();
private JMenu file = new JMenu("File");
private int selecteditem=0;
private void setlabels()
{
labels = new JLabel[lnames.length];
for (int i =0; i < lnames.length; i++)
{
labels[i] = new JLabel(lnames[i]);
labels[i].setHorizontalAlignment(SwingConstants.CENTER);
labels[i].setEnabled(false);
}
}
private void setbuttons()
{
buttons = new JButton[bnames.length];
for (int i=0; i< bnames.length; i++)
{
buttons[i] = new JButton( bnames[i]);
buttons[i].addActionListener(this);
}
}
private void settextfield()
{
tfields = new JTextField[lnames.length];
for (int i=0; i < lnames.length; i++)
{
tfields[i] = new JTextField(INFO_SIZE);
tfields[i].setEnabled(false);
}
}
private void setbutton2(){
buttons2 = new JButton[bnames2.length];
for (int i =0; i < bnames2.length; i++)
{
buttons2[i] = new JButton(bnames2[i]);
buttons2[i].addActionListener(this);
}
}
private void setmenubar()
{
menuitems = new JMenuItem[mnames.length];
for (int i=0; i <mnames.length; i++)
{
menuitems[i] = new JMenuItem(mnames[i]);
menuitems[i].addActionListener(this);
}
}
public CheckoutGUI(Checkout checkout)
{
super("CheckoutGUI");
checkout = this.checkout;
setSize(600,300);
setLocation(200,200);
setlabels();
setbuttons();
settextfield();
setbutton2();
setmenubar();
ContainerSetup();
show();
}
public void actionPerformed( ActionEvent e)
{
Object source = e.getSource();
if (source == menuitems[0]) //Clear
{
checkout.clear();
_info.setText("Number of Items: 0");
resetinfo();
inablebuttonsAll();
disableinfoAll();
}
else if (source == menuitems[1]) //Exit
{
System.exit(1);
}
else if (source == buttons[0]) // Ice Cream
{
inableinfo(0); //name
inableinfo(1); //price
selecteditem=0;
}
else if (source == buttons[1]) //Candy
{
inableinfo(0); //name
inableinfo(3); //price/lbs
inableinfo(2); //weight
selecteditem=1;
}
else if (source == buttons[2]) //Cookie
{
inableinfo(0); //name
//inableinfo(1); //price
inableinfo(4); //price/doz
inableinfo(5); //number
selecteditem=2;
}
else if (source == buttons[3]) //Sundae
{
inableinfo(0); //name
inableinfo(1); //price
inableinfo(6); // topping
inableinfo(7); // topping cost
selecteditem=3;
}
else if (source == buttons2[0]) //Enter
{
inablebuttonsAll();
disableinfoAll();
try
{
switch (selecteditem)
{
case 0: //Ice Cream
checkout.enterItem( new IceCream(
tfields[0].getText(),
Integer.parseInt(tfields[1].getText())
));
break;
case 1: //Candy
checkout.enterItem( new Candy(
tfields[0].getText(),
Double.parseDouble(tfields[2].getText()),
Integer.parseInt(tfields[3].getText()) ));
break;
case 2: //Baked Goods
checkout.enterItem( new Cookie(
tfields[0].getText(),
Integer.parseInt(tfields[5].getText()),
Integer.parseInt(tfields[4].getText()) ));
break;
case 3: //Sundae
checkout.enterItem( new Sundae(
tfields[0].getText(),
Integer.parseInt(tfields[1].getText()),
tfields[6].getText(),
Integer.parseInt(tfields[7].getText()) ));
break;
} // end switch
_info.setText("Number of items: "+checkout.numberOfItems());
} // end try
catch (Exception ref)
{
_info.setText("Invalid Entry, Number of Items: "
+ checkout.numberOfItems());
}
finally
{
resetinfo();
}
}
else if (source == buttons2[1]) //Total
{
ReceiptGUI r = new ReceiptGUI(checkout.toString());
checkout.clear();
_info.setText("Number of Items: 0");
resetinfo();
inablebuttonsAll();
disableinfoAll();
}
for (int i=0; i <buttons.length; i++) //types
{
if (source == buttons[i])
{
disablebuttons(i);
}
}
}
private void resetinfo()
{
for (int i=0; i< lnames.length; i++)
{
tfields[i].setText("");
}
}
private void disablebuttons(int b)
{
for (int i=0; i< buttons.length; i++)
{
if (b != i) buttons[i].setEnabled(false);
}
}
private void inablebuttonsAll()
{
for (int i=0; i< buttons.length; i++)
{
buttons[i].setEnabled(true);
}
}
private void inableinfo(int b)
{
for (int i=0; i< lnames.length; i++)
{
if (b ==i)
{
labels[i].setEnabled(true);
tfields[i].setEnabled(true);
}
} // end for
}
private void disableinfoAll()
{
for (int i=0; i <lnames.length; i++)
{
labels[i].setEnabled(false);
tfields[i].setEnabled(false);
}
}
class ReceiptGUI
{
private JTextArea text = new JTextArea();
private JFrame receipt = new JFrame("Receipt");
public ReceiptGUI(String info)
{
Container p = receipt.getContentPane();
receipt.setSize(235,600);
p.add(new JScrollPane(text),BorderLayout.CENTER);
text.setText(info);
text.setEditable(false);
text.setFont(new Font("Monospaced",Font.PLAIN,12));
receipt.show();
}
}
private void ContainerSetup()
{
Container c = getContentPane();
for (int i=0; i< mnames.length; i++) file.add(menuitems[i]);
bar.add(file);
setJMenuBar(bar);
_info.setEditable(false);
_info.setBackground(Color.white);
c.add(_info,BorderLayout.NORTH);
JPanel spanel = new JPanel();
for (int i=0; i < bnames2.length; i++) spanel.add(buttons2[i]);
c.add(spanel,BorderLayout.SOUTH);
JPanel cpanel = new JPanel();
cpanel.setBorder(BorderFactory.createLoweredBevelBorder());
cpanel.setLayout(new GridLayout(lnames.length,2));
for (int i=0; i < lnames.length; i++)
{
cpanel.add(labels[i]);
cpanel.add(tfields[i]);
}
c.add(cpanel,BorderLayout.CENTER);
JPanel wpanel = new JPanel();
wpanel.setLayout(new GridLayout(4,0));
for (int i=0; i< bnames.length; i++) wpanel.add(buttons[i]);
c.add(wpanel,BorderLayout.WEST);
}
public static void main (String args[] )
{
CheckoutGUI app = new CheckoutGUI(new Checkout());
app.addWindowListener( new WindowAdapter()
{
public void windowClosing(WindowEvent e) { System.exit(0); }});
}
} // end CheckoutGUI
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.