I am working on an assignment "Dessert Shoppe" and basically what I need to do is to create DessertItem subclasses Candy, Cookie, IceCream, Sundae and Checkout. I am also provided with DessertItem class & DessertShoppe and I am not allowed to modify them.
While I have created all these subclasses, when I run it on my TestCheckout.java , it will not work but rather display getName() in Sundae cannot override getName() in DessertItem.
public final String getName(){
^
overriden method is final.
I will provide you guys all the classes that I have made now.
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 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 Cookie extends DessertItem{
protected double number;
protected double pricePerDoze;
public Cookie(String _n, double _ppd, int _number){
super(_n);
pricePerDoze = _ppd;
number = _number;
}
public int getCost(){
return (int)Math.round(number / 12 * pricePerDoze);
}
}
public class Candy extends DessertItem{
protected double weight;
protected double pricePerPound;
public Candy(String _n, double _ppp, int _w){
//using parent's constructor with name while storing its own properties
super(_n);
pricePerPound = _ppp;
weight = _w;
}
public int getCost(){
return (int)Math.round(weight * pricePerPound);
}
}
public class IceCream extends DessertItem{
protected int cost;
public IceCream(String _n, int _cost){
super(_n);
cost = _cost;
}
public int getCost(){
return cost;
}
}
public class Sundae extends IceCream{
protected String topName;
protected int topCost;
public Sundae(String _n0, int _cost0, String _n1, int _cost1){
//put the icecream name in icecream while putting top name and cost in a separate property
super(_n0, _cost0);
topName = _n1;
topCost = _cost1;
}
public final String getName(){
//return both the icecream name and the topping name
return name + " " + topName;
}
public int getCost(){
//return the sum of the icecream and the topping
return cost + topCost;
}
}
public class Checkout{
protected int size;
protected DessertItem[] dessertItems;
protected int amount;
protected int sum;
protected final double taxRate;
Checkout(){
size = 100;
dessertItems = new DessertItem[size];
amount = 0;
sum = 0;
taxRate = DessertShoppe.TAX_RATE;
}
public void enterItem(DessertItem d){
dessertItems[amount] = d;
amount ++;
}
public int numberOfItems(){
return amount;
}
public int totalCost(){
//make sum into zero, and calculate price from every item
sum = 0;
for(int i = 0; i < amount; i ++){
sum += dessertItems[i].getCost();
}
return sum;
}
public int totalTax(){
//use the totalCost method
return (int)(Math.round(this.totalCost() * taxRate / 100));
}
public void clear(){
//clear the array
for(DessertItem d : dessertItems){
d = null;
}
amount = 0;
sum = 0;
}
public String toString(){
String result = "Thank You! \n";
result += DessertShoppe.STORE_NAME + "\n";
result += "Purchased: ";
String totalPay = DessertShoppe.cents2dollarsAndCents( totalCost()+totalTax() );
if(totalPay.length() > DessertShoppe.COST_WIDTH){
totalPay = totalPay.substring(0, DessertShoppe.COST_WIDTH);
}
result += "$" + totalPay;
return result;
}
}
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("\nNumber of items: " + checkout.numberOfItems() + "\n");
System.out.println("\nTotal cost: " + checkout.totalCost() + "\n");
System.out.println("\nTotal tax: " + checkout.totalTax() + "\n");
System.out.println("\nCost + Tax: " + (checkout.totalCost() + checkout.totalTax()) + "\n");
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("\nNumber of items: " + checkout.numberOfItems() + "\n");
System.out.println("\nTotal cost: " + checkout.totalCost() + "\n");
System.out.println("\nTotal tax: " + checkout.totalTax() + "\n");
System.out.println("\nCost + Tax: " + (checkout.totalCost() + checkout.totalTax()) + "\n");
System.out.println(checkout);
}
}
The expected output should be:
Number of items: 4
Total cost: 1331
Total tax: 87
Cost + Tax: 1418
M & M Dessert Shoppe
--------------------
2.25 lbs. # 3.99 /lb.
Peanut Butter Fudge 8.98
Vanilla Ice Cream 1.05
Hot Fudge Sundae with
Choc. Chip Ice Cream 1.95
4 # 3.99 /dz.
Oatmeal Raisin Cookies 1.33
Tax .87
Total Cost 14.18
Number of items: 6
When a method is marked as final, it means that it cannot be overridden in a subclass.
Therefore, you need to use the getName() method as it stands, and figure out how to get the appropriate value into the name variable.
Luckily, there's a constructor in IceCream that does that, so all you need to do is pass into the constructor what you want getName() to return (and what you want getCost() to return):
public Sundae(String _n0, int _cost0, String _n1, int _cost1){
super(_n1 + " Sundae with\n" + _n0, _cost0 + _cost1);
}
This way, your Sundae class doesn't need a getName() or a getCost() method.
As stated in other answers, the final modifier means that the method cannot be overridden by any of its subclasses.
There are two ways around this:
The first is to pass the arguments into the Sundae constructor as shown by Jason:
super(_n0 + " " + _n1, _cost0 + _cost1);
The second would be to utilize the fact that Sundae is a subclass of IceCream, which is a subclass of DessertItem. The name field is protected, meaning that you could directly access the field from the constructor.
Keep in mind, that with the second option, you will need to explicitly check to make sure that the name you provide is shorter than DessertShoppe.MAX_ITEM_NAME_SIZE to keep in line with that standard length.
The simpler and probably intended solution would be the first one, though both are valid.
Related
New to java and I'm confused as to how I can combine these two objects. Sorry if I am not clear / if this has been asked before.
I need to add one.PiggyBank to two.PiggyBank
We are not allowed to change the program used to output the code
public class PiggyBank {
doubles pennies, nickels, dimes, quarters, totalValue, bankTotal;
public PiggyBank(int p, int n, int d, int q)
{
pennies = p;
nickels = n;
dimes = d;
quarters = q;
totalValue = pennies + nickels + dimes + quarters;
}
public void addPenny()
{
}
//accessors
public double getP()
{
return pennies;
}
public double getN()
{
return nickels;
}
public double getD()
{
return dimes;
}
public double getQ()
{
return quarters;
}
public double combinePiggy(double bank2)
{
two.
bankTotal = bank1 + bank2;
}
public static void main(String[] args) {
PiggyBank one = new PiggyBank(5, 5, 5, 5);
PiggyBank two = new PiggyBank(2, 3, 4, 1);
System.out.println(“Account 1: “ + one + “\n”);
System.out.println(“Account 2: “ + two + “\n”);
one.combinePiggy(two);
System.out.println(“Account 1: “ + one + “\n”);
System.out.println(“Account 2: “ + two + “\n”);
}
}
You need to create that combinePiggy(PiggyBank) method and then add the values of the parameter to the corresponding values you call this on.
Somewhat abstract and simplified example to get you started (you should do the real thing yourself to have a learning effect):
class Thing {
int x;
int y;
void combine(Thing otherThing) {
x += otherThing.x;
y += otherThing.y;
}
}
There is so much wrong with this. First of all, it does not make sense to have those attributes listed as type double.
For example: pennies = 0.5; this makes no sense, as you cannot have half a penny in a piggy bank. This needs to be adjusted for all accessor and mutator methods.
public class PiggyBank {
int pennies, nickels, dimes, quarters;
double bankTotal;
.
.
.
public int getP()
{
return pennies;
}
public int getN()
{
return nickels;
}
public int getD()
{
return dimes;
}
public int getQ()
{
return quarters;
}
}
Additionally, the combinePiggy method should not have a return type, as you are not returning anything. Furthermore, as the main method suggests, the combinePiggy method should have another piggybank as a parameter. The method should then add the number of each piggy bank together, as well as the total of each bank.
public void combinePiggy(PiggyBank bank2)
{
pennies += bank2.pennies;
nickels += bank2.nickels;
dimes += bank2.dimes;
quarters += bank2.quarters;
bankTotal += bank2.bankTotal;
}
Another thing, judging by the main method, your class needs a toString method. A toString method is exactly what the name implies. It converts an object into a string. (I'll leave it for you to write the appropriate toString to fit your main method)
public String toString(){
return "This piggy bank has " + pennies + " pennies, " + nickels + " nickels, " +
dimes + " dimes, " + quarters + " quarters.";
}
Also, you cannot just add the number of coins in order to get a bank total. Example: You have a penny, a nickel, a dime and a quarter. 0.01+0.05+0.10+0.25=0.41. The way you are doing it, you're bank total would just add up the number of coins.
public PiggyBank(int p, int n, int d, int q)
{
pennies = p;
nickels = n;
dimes = d;
quarters = q;
bankTotal = pennies*0.01 + nickels*0.05 + dimes*0.1 + quarters*0.25;
}
I think I've done more than answer your question. I will leave the addPenny as well as the setter methods to you. It seems you are very new to Java. I suggest you watch a few videos and read some documentation about the language before you tackle this assignment. Here is a video that more or less sums up the language.
I'm nearly finished with a program I've been writing for quite some time for a school final assignment. It's 99% complete, but I'd like to add a couple things to make it as perfect as possible and need help.
I'd like to display the final price of an order in currency format, but have only figured out a way to format as currency if it's in my tostring method.
There's also bonus points to be had with this if I create a method that creates an order from a file. (ex: orders 1 Reece's Pieces, 6 sugar cookies, 1 chocolate chip cookie, and 1 scoop of caramel ice cream).
Here's my code. Any help is appreciated.
package dessertshop;
import java.text.NumberFormat;
import java.util.Scanner;
abstract class DessertItem
{
protected String name;
public DessertItem()
{
this.name = "";
}
public DessertItem( String name )
{
this.name = name;
}
public final String getName()
{
return name;
}
public abstract double getCost(int number);
}
class Candy extends DessertItem
{
private double pricePerPound;
public Candy( String name, double unitPrice )
{
super( name );
this.pricePerPound = unitPrice;
}
#Override
public double getCost(int amount)
{
return( amount * pricePerPound );
}
public String toString()
{
NumberFormat formatter = NumberFormat.getCurrencyInstance();
return( "Candy\t" + name + "\t # " + formatter.format( this.pricePerPound ) + " per pound");
}
}
class Cookie extends DessertItem
{
private double pricePerDozen;
public Cookie(String name, double pricePerDozen)
{
super(name);
this.pricePerDozen=pricePerDozen;
}
#Override
public double getCost(int amount)
{
return(amount * pricePerDozen)/12;
}
public String toString()
{
NumberFormat formatter = NumberFormat.getCurrencyInstance();
return( "Cookie\t" + name + "\t # " + formatter.format( this.pricePerDozen) + " per dozen");
}
}
class IceCream extends DessertItem
{
private double cost;
public IceCream(String name, double cost)
{
super(name);
this.cost=cost;
}
#Override
public double getCost(int amount)
{
return(amount * cost);
}
public String toString()
{
NumberFormat formatter = NumberFormat.getCurrencyInstance();
return( "Ice Cream\t" + name + "\t # " + formatter.format( this.cost ) + " per scoop");
}
}
public class DessertShop
{
private String name = "";
private DessertItem[] menu;
private int numberOfItems = 0;
public DessertShop(String name)
{
this.name = name;
menu = new DessertItem[200];
}
public DessertShop()
{
menu = new DessertItem[200];
}
public void addToMenu(DessertItem item)
{
menu[numberOfItems++] = item;
}
public void printMenu()
{
System.out.println(this.toString());
for (int i = 0; i < numberOfItems; i++)
{
System.out.print((i + 1) + ": " + menu[i].toString());
System.out.println("");
}
}
public double createNewOrder()
{
double totalCost = 0;
Scanner input = new Scanner(System.in);
while (true)
{
this.printMenu();
System.out.print("What would you like to purchase? (0 to checkout) > ");
int choice = input.nextInt();
if (choice == 0)
{
break;
}
System.out.print("How many (lbs. or amount) > ");
int amount = input.nextInt();
totalCost += menu[(choice - 1)].getCost(amount);
}
input.close();
return totalCost;
}
public String toString()
{
return ("Welcome to " + name);
}
public static void main( String[] args )
{
DessertShop shop01 = new DessertShop("Chuck D's Dessert Depot");
Candy candy01 = new Candy("Reece's Pieces", 3.99);
Candy candy02 = new Candy("Chocolate Covered Raisins", 4.99);
Cookie cookie01 = new Cookie("Peanut Butter", 5.99);
Cookie cookie02 = new Cookie("Chocolate Chip", 4.99);
Cookie cookie03 = new Cookie("Sugar", 4.50);
IceCream icecream01 = new IceCream("Cookie Dough", 3.00);
IceCream icecream02 = new IceCream("Vanilla", 2.00);
IceCream icecream03 = new IceCream("Caramel", 3.50);
IceCream icecream04 = new IceCream("Rocky Road", 2.99);
IceCream icecream05 = new IceCream("Mint Chocolate Chip", 3.99);
shop01.addToMenu(candy01);
shop01.addToMenu(candy02);
shop01.addToMenu(cookie01);
shop01.addToMenu(cookie02);
shop01.addToMenu(cookie03);
shop01.addToMenu(icecream01);
shop01.addToMenu(icecream02);
shop01.addToMenu(icecream03);
shop01.addToMenu(icecream04);
shop01.addToMenu(icecream05);
double frankOrder = shop01.createNewOrder();
System.out.println(frankOrder);
}
}
Depending on what you seek, you can format your price at your last line of code:
System.out.println(frankOrder)
have a look: here.
About the other question, reading in from file, I suggest you have a look at csv files: here and how to read them:here
If you don't want to hassle too much, you can get decent result with printf:
System.out.printf("Price is: €%,d", 12342353563623L);
Output is: Price is: €12,342,353,563,623
Formatter on "," flag:
The result will include locale-specific grouping separators
I have a program with different types of tickets. I have the Ticket, AdvanceTicket, and a StudentAdvanceTicket. I am printing the price of the ticket $50, advance ticket both options $30 and $40), and both options for student advance tickets $15 and $20.
Both options with the condition being if daysAhead >= 10.
I'v spent hours trying to solve this, I need help.
Ticket.java
public class Ticket {
private int number;
public Ticket(int number) {
this.number = number;
}
public double getPrice() {
return 50.0;
}
public String toString() {
return "Ticket #" + this.number + ", Price: $" + this.getPrice();
}
}
TicketMain.java
public class TicketMain {
public static void main(String[] args) {
Ticket[] tickets = new Ticket[5];
tickets[0] = new WalkupTicket(1);
tickets[1] = new AdvanceTicket(2,12);
tickets[2] = new AdvanceTicket(3,8);
tickets[3] = new StudentAdvanceTicket(4,17);
tickets[4] = new StudentAdvanceTicket(5,7);
for (int i = 0; i<5; i++) {
System.out.println(tickets[i]);
//System.out.println(" ");
}
}
}
AdvanceTicket.java
public class AdvanceTicket extends Ticket {
private int daysAhead;
public AdvanceTicket(int number, int daysAhead) {
super(number);
this.daysAhead = daysAhead;
}
public double getPrice() {
if (daysAhead >= 10) {
return 30.00;
} else {
return 40.00;
}
}
public String toString() {
if (daysAhead >= 10) {
return super.toString() + " (" + this.daysAhead + " days ahead, you got a great deal!)";
} else {
return super.toString() + " (" + this.daysAhead + " days ahead, you could have saved a bit more)";
}
}
}
And finally the issue...
StudentAdvanceTicket.java
public class StudentAdvanceTicket extends AdvanceTicket {
public StudentAdvanceTicket(int number, int daysAhead) {
super(number, daysAhead);
super.price = super.getPrice() / 2;
}
public String toString() {
return super.toString() + " (ID Required) ";
}
}
This is my desired output.
Ticket #1, Price: $50.0
Ticket #2, Price: $30.0 (12 days ahead, you got a great deal!)
Ticket #3, Price: $40.0 (8 days ahead, you could have saved a bit more)
Ticket #4, Price: $15.0 (ID Required)
Ticket #5, Price: $20.0 (ID Required)
When you call getPrice() for a StudentAdvanceTicket, your program actually calls the implementation from AdvanceTicket, which will return $30 or $40.
Now when you call toString() for a StudentAdvanceTicket, it calls toString from the super, which is the one for AdvanceTicket, and that one calls the object's getPrice() method, which, again, just returns $30 or $40 and doesn't make use of the price member variable.
The correct solution is to override getPrice for the StudentAdvanceTicket class. In that method, you call super.getPrice() and then do the price manipulation with that.
In StudentAdvanceTicket there is a compile error because super.price cannot be resolved.
public class Purchase
{
int invoiceNumber = 1234;
double salePrice = 10.00;
double SalesTax;
public void setInvoiceNumber(int invoice)
{
invoiceNumber = invoice;
}
public void setSalePrice(double saleAmount)
{
salePrice = saleAmount;
SalesTax = (saleAmount * .05);//when I'm compiling it's not calculating
}
public void displaySalePrice()
{
System.out.println("Your invoice number is:" + invoiceNumber + ".");
System.out.println("Your sale amount is: " + salePrice + ".");
System.out.println("Your sales tax is: " + SalesTax + ".");
}
}
Your invoice number is:1234.
Your sale amount is: 10.0.
Your sales tax is: 0.0.-------Problem area
----jGRASP wedge2: exit code for process is 0.
----jGRASP: operation complete.
This will work...
public class Purchase
{
int invoiceNumber = 1234;
double salePrice = 10.00;
double SalesTax = 0.0; // by default this is initialized to zero.
public void setInvoiceNumber(int invoice)
{
invoiceNumber = invoice;
}
public void setSalePrice(double saleAmount)
{
salePrice = saleAmount;
SalesTax = (saleAmount * .05);//when I'm compiling it's not calculating
}
public void displaySalePrice()
{
System.out.println("Your invoice number is:" + invoiceNumber + ".");
System.out.println("Your sale amount is: " + salePrice + ".");
System.out.println("Your sales tax is: " + SalesTax + ".");
}
public static void main(String args[])
{
setSalePrice(10.0); // sets SalesTax to (100.0 * .05)
displaySalePrice();
}
}
Note that there are some stylistic issues with this class.
"SalesTax" starts with an upper case letter, which is supposed to be reserved for class (and interface) names. The correct spelling is "salesTax".
It lacks a constructor.
Example Constructor:
public Purchase(int invoiceN, double salesP, doubles salesT) {
invoiceNum = invoiceN;
salesPrice = salesP;
salesTax = salesT;
}
A purchase is a thing that doesn't change once it is made. Its data members are variable (change-able), but they should be invariable (final or constant).
final int invoiceNumber; // These are set in the Constructor.
final double salePrice; // Once they are set, they don't change.
final double salesTax;
The class has setters (which set/change the variables), but it lacks getters (which retrieve the values of the variables without changing them). In general, variables should be declared "private" and "final" whenever possible. So if I wrote this class, I would have written it like this:
Revised example:
public class Purchase
{
private final int invoiceNumber;
private final double salePrice;
private final double salesTax;
// Constructor
public Purchase(int invoiceN, double salesP) {
invoiceNum = invoiceN;
salesPrice = salesP;
salesTax = salesPrice * .05; // The Constructor can figure this out.
}
public int getInvoiceNumber()
{
return this.invoiceNumber; // "this." is optional
}
public double getSalePrice()
{
return this.salePrice();
}
public double getSalesTax()
{
return this.salesTax;
}
public void displaySalePrice()
{
System.out.println("Your invoice number is:" + getInvoiceNumber() + ".");
System.out.println("Your sale amount is: " + getSalePrice() + ".");
System.out.println("Your sales tax is: " + getSalesTax() + ".");
}
public static void main(String args[])
{
Purchase shoesPurchase = new Purchase(1234, 10.00);
shoesPurchase.displaySalePrice();
}
}
You are never using the setSalePrice method, hence your SalesTax parameter is never being initialized. You could initialize it like so: double SalesTax = salePrice * 0.05;
You are never calling setSalePrice, so the sales tax never gets set
here's one way to correct this, though really you should probably call setSalePrice before calling displaySalePrice, rather than inside of it
public void displaySalePrice()
{
setSalePrice(salePrice);
System.out.println("Your invoice number is:" + invoiceNumber + ".");
System.out.println("Your sale amount is: " + salePrice + ".");
System.out.println("Your sales tax is: " + SalesTax + ".");
}
I have my code running perfectly, except for my return value for the monthly loan calculator. It keeps on returning Infinity for both my monthly payments and total payments. Please help with the formula. This is a homework. All i need to know is if I am implementing the formula incorrectly. I get the feeling that it is somehow trying to divide over 0 and then returning infinity, but I could be wrong.
public class MyLoan
{
private double amountBorrowed;
private double yearlyRate;
private int years;
public double A;
public double n = years * 12;
public MyLoan(double amt, double rt, int yrs)
{
amountBorrowed = amt;
yearlyRate = rt;
years = yrs;
}
public double getAmountBorrowed()
{
return amountBorrowed;
}
public double getYearlyRate()
{
return yearlyRate;
}
public int getYears()
{
return years;
}
public double monthlyPayment()
{
double i = (yearlyRate / 100) / 12;
A = (amountBorrowed) * (i * Math.pow(1+i, n)) / (Math.pow(1+i, n) -1);
return A;
}
public double totalPayment()
{
return A * (years * 12);
}
public String toString()
{
return "Loan: " + "$" + amountBorrowed + " at " + yearlyRate + " for " + years + " years";
}
public static void main(String[] args)
{
final double RATE15 = 5.75;
final double RATE30 = 6.25;
StdOut.println("***** Welcome to the Loan analyzer! *****");
String ans = "Y";
do {
StdOut.print("\n Enter the principle amount to borrow: ");
double amount = StdIn.readDouble();
MyLoan fifteenYears = new MyLoan(amount, RATE15, 15);
MyLoan thirtyYears = new MyLoan(amount, RATE30, 30);
double amount15 = fifteenYears.monthlyPayment();
double total15 = fifteenYears.totalPayment();
double amount30 = thirtyYears.monthlyPayment();
double total30 = thirtyYears.totalPayment();
StdOut.println("===========ANALYSES==========");
StdOut.println(fifteenYears);
StdOut.println("Monthly payment = " + "$" + amount15);
StdOut.println("Total payment = " + "$" + total15);
StdOut.println("");
StdOut.println("");
StdOut.println(thirtyYears);
StdOut.println("Monthly payment = " + "$" + amount30);
StdOut.println("Total payment = " + "$" + total30);
StdOut.println("=============================");
StdOut.print("\n ** Do you want to continue (y/n)? ");
ans = StdIn.readString();
} while (ans.toUpperCase().equals("Y"));
StdOut.println("\n********** Thank you. Come again! **********");
}
}
You should be debugging this yourself, but I'll give you a hint. What is 1^n (where n is a positive integer)? Where, in your code, are you using this construct?
There is many ways to calculate interest and the most common is just
A = amountBorrowed * (yearlyRate / 100) / 12;