Abstract Concept Assignment [closed] - java

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
So my questions are geared directly to my homework. Before you ask, yes I've looked at other questions and I have looked at the java docs to try and help me but I only understand so much..
You have become a restaurant mogul. You own several fast food chains. However, you now need to set a standard that all of your fast food chain must follow in order to have your software be uniform across the board. There will be some rules that will be the same for all restaurants.
Create an Abstract Class named Restaurant
Create a function/method that will print the name of the restaurant when called.
Create an abstract function/method named total price
Create an abstract function/method named menu items
Create an abstract function/method name location
Create a Class called McDonalds that extends Restaurant
Implement all abstract methods
Add logic so that the total price method/function will give the total price of the meal including a 6% tax
Add a method that returns a Boolean named hasPlayPlace. Which returns true when this location has a playplace
Create a Constructor that will set the name of the Mcdonalds, location, and hasPlayPlace
public class McDonalds extends Restaurant {
private String name;
private String location;
private boolean hasPlayPlace;
Scanner input = new Scanner(System.in);
public McDonalds (String name, String location, boolean hasPlayPlace) {
setName(name);
setLocation(location);
setHasPlayPlace(hasPlayPlace);
}
McDonalds location1 = new McDonalds("McDonalds", "Kirkman", false);
McDonalds location2 = new McDonalds("McDonalds 2", "International Dr.", true);
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLocation() {
return location;
}
public void setLocation(String location){
this.location = location;
}
public boolean isHasPlayPlace() {
return hasPlayPlace;
}
public void setHasPlayPlace(boolean hasPlayPlace) {
this.hasPlayPlace = hasPlayPlace;
}
public void totalPrice() {
double totalPrice = 0;
double tax = 0.06;
totalPrice += (totalPrice * tax);
}
public void menuItems() {
//some syntax is wrong in this method
double mcChicken = 1;
double fries = 1.25;
System.out.println("1. Mc Chicken $1");
System.out.println("2. Fries $1.25");
int choice = input.nextInt();
switch (choice){
case 1: mcChicken *= tax;
case 2: fries *= tax;
}
}
public void location() {
//Don't know what's supposed to go in here.
//But I've implemented the method as I was supposed to.
}
}
Does it all make sense is basically what i'm asking.
What should go in the location method?
What's the use of getters and setters within this class and did I do it right?

1) Your constructor is structured fine, but you should use Strings instead of chars for the name and location. A char will only hold one character.
2) You can create multiple instances of a class:
McDonalds location1 = new McDonalds("McDonald", "Kirkman", true);
McDonalds location2 = new McDonalds("McDonald2", "Kirkman", false);
3) You should add the tax to the price as a percentage, not a sum: price * 1.06. Be careful not to change the price w/o tax when you print the total price.

Name and location should be String not char.
I like the style of calling setters from within the constructor, because its a form of code reuse, especially if there are special checks being made on those values, such as not being null - calling he setter means you only check this in one place.
Your code won't compile, but you're close:
McDonalds location1 = new McDonalds("Some name", "Kirkman", true);
Your calculation is a little off too:
double tax = 0.06;
totalPrice *= (tax + 1);
However, this is dangerous because if called twice, it will add the tax twice. It would be better to have a method return the tax included price which calculates it every time. Having a getter with side effects is a design error. Ie have thus:
public double getTaxIncPrice() {
double tax = 0.06;
return totalPrice * (1 + tax);
}

In addition to the problem that Bohemian pointed out (name and location should be String, not char):
Your constructor call will need quotes on the String parameters:
McDonalds location1 = new McDonalds("McDonald", "Kirkman", true);
and your tax calculation is incorrect - you will need to multiply the total amount by the tax percentage, and you will have to wait until you actually have a total to do the calculation.

Just editted my code and provided the question. Your guys inputs helped so far.
public String TacoBellSauce(String fire, String hot, String mild) {
System.out.println("What sauce would you like to have?");
System.out.println("1. Fire");
System.out.println("2. Hot");
System.out.println("3. Mild");
int choice = input.nextInt();
switch(choice) {
case 1:
return fire;
case 2:
return hot;
case 3:
return mild;
}
return null;
}
Here is also my method for the TacoBell class. How would I return it in the Test class? It says to make a method within TacoBell that returns a string of what hot sauce I would like. But then it says within the test class to call hotsauce and return hot. I haven't created that class yet cause I'm focused on correcting everything with McDonalds and TacoBell.

Related

Update constructor using method

I have a game app and I want it to update the constructor strength value when I call the levelUp() method.
public Hero(String heroname, double strength, double strength_gain){
this.heroname = heroname;
this.hp = (int) (200+20*strength);
this.strength_gain = strength_gain;
}
public void levelUp(){
this.strength = strength + strength_gain;
}
But when i do System.out.println(hero.hp); after calling levelUp() it returns the first value.
One way to always get an up-to-date value for a calculation that depends on other variables/inputs is to calculate it on demand (useful for simple calculations, such as the one you have).
EDIT: I realized that you might want to have an hp and a maxHp if your hero can actually lose/gain hp so I edited the example to take that into account.
public class Hero {
// ...
public int hp;
public Hero(String heroname, double strength, double strength_gain){
this.heroname = heroname;
this.strength = strength; // <-- don't forget to save the initial strength as well
this.strength_gain = strength_gain;
this.hp = getMaxHp();
}
public int getMaxHp() {
return (int) (200 + 20 * strength);
}
public void levelUp(){
strength = strength + strength_gain;
// decide if leveling up also heals your hero?
hp = getMaxHp();
}
// ...
}
Elsewhere in code you can access both the .hp and the .getMaxHp().
System.out.println(hero.hp);
System.out.println(hero.getMaxHp());
If the calculations would be heavy, then using a boolean as a change flag and lazily recalculating only once per change and only when required would make more sense.

Creating a Vehicle Program

Right now I'm doing some tasks from a java e-book that I've acquired, and unfortunately, I'm stuck. The main thought of this program is to create a Vehicle class, which along with a test program can increase, decrease and break the current speed.
The starting speed should be 0. I want the user to specify what speed the car should drive to (for an example 90 km/h). After hitting the speed(90 in this case) I want the program to ask the user if he wants to decrease the speed to a given value, stay at the same speed, or break to 0. Should all of this be done in the testprogram, or should it be implemented into the Vehicle class?
I'm supposed to create a program from the following UML: https://i.stack.imgur.com/01fgM.png
This is my code so far:
public class Vehicle {
int speed;
//Constructor
public Vehicle () {
this.speed = 0;
}
public void increaseSpeed (int differenceInc) {
this.speed += differenceInc;
}
public void decreaseSpeed (int differenceDec) {
this.speed -= differenceDec;
}
public void brake() {
}
public int getSpeed () {
return this.speed;
}
}
And this is my empty test class.
public class VehicleTest {
public static void main(String[] args) {
Vehicle golf = new Vehicle();
//Speed which should be accelerated to:
Vehicle myHybrid = new Vehicle();
System.out.println("You've hit the given speed. Do you want to stay at this speed, break, or decrease to another given speed?");
}
}
Well , first of all, welcome to Stack Overflow.
If you want a method to accept arguments (parameters) then you must declare said arguments and the arguments' types in the mehtod declaration:
public void increaseSpeed (int augmentValue) {
this.speed += augmentValue;
}
You're also asking about software design: "should the component (Vehicle) user or client be able to set the augment value of the increaseSpeed mehtod?" . The answer relies on the design of said component. If your method will accept an argument then perhaps the method should also validate the input value and establish pre and post conditions.
Hope this helps.
Probably the idea is to take an int for increaseSpeed(), so that you can increase the speed by that given integer. Also add the logic for hitting the speed limit in your increaseSpeed method.
So...
public void increaseSpeed (int amount) {
if (speed + amount < MAX_SPEED) { // Where MAX_SPEED is a static final int of value 90
this.speed += amount;
} else {
System.out.println("Max speed reached. Want to exceed (y/n)?");
Scanner scanner = new Scanner(System.in);
char c = scanner.next().charAt(0);
if (c == 'y') {
this.speed += amount;
}
}
}
You can do the same for decreaseSpeed(), of course. Don't forget to check if decreasing the speed doesn't result in a negative speed (unless, you consider a negative value of speed to be driving in reverse.
By the way, here I have hard-coded MAX_SPEED for simplicity. This is, of course, dependent on the road you are driving, so it is probably better to do this differently (e.g., a Road class that includes the particular attributes of a given road, or by passing both an integer for the amount you want to speedup with and an integer for the maximum speed).

How to make calculation inside class field in Java?

So I created Saving class, created also setters and getters. Now I need u method, which will calculate the total amount of deposits.
public class Saving {
private double deposits;
private double totalAmountOfDeposits;
public double getDeposits()
{
return deposits;
}
public void setDeposits(double deposits)
{
this.deposits = deposits + deposits;
}
public double getTotalAmountOfDeposits()
{
double total = 0;
return total = total + deposits;
}
}
When I use this class in the program I got a wrong calculation. The program just add first value of deposit to the first value.
import java.util.Scanner;
public class SavingDemo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Saving save = new Saving();
System.out.println("Deposit amount");
double depositeAmount = input.nextDouble();
save.setDeposits(depositeAmount);
System.out.println("Deposit amount");
double depositeAmount2 = input.nextDouble();
save.setDeposits(depositeAmount);
System.out.println("Deposit amount");
double depositeAmount3 = input.nextDouble();
save.setDeposits(depositeAmount);
System.out.println("The total amount has been deposited is " + save.getTotalAmountOfDeposits());
}
}
And here is the output:
Deposit amount
12
Deposit amount
34
Deposit amount
56
The total amount has been deposited is 24.0
As you can see its just added 12 to 12. Just want to mention that I'm totally new in programming. Les than a month.
I see two problems in your code. Take a look at the commented line. The reason you are seeing 12 + 12 is because that is exactly what you are instructing the JVM to do.
System.out.println("Deposit amount");
double depositeAmount = input.nextDouble();
save.setDeposits(depositeAmount);
System.out.println("Deposit amount");
double depositeAmount2 = input.nextDouble();
save.setDeposits(depositeAmount); // <= adds the wrong variable
System.out.println("Deposit amount");
double depositeAmount3 = input.nextDouble();
save.setDeposits(depositeAmount); // <= adds the wrong variable
System.out.println("The total amount has been deposited is " + save.getTotalAmountOfDeposits());
Secondly, it looks like you may have a design flaw in your implementation of the Saving class.
You'll want to brush up on variable scope
If you take a look at your implementation on your total:
public double getTotalAmountOfDeposits()
{
double total = 0;
return total = total + deposits;
}
You have the total starting at 0 every time this method getTotalAmountOfDeposits() is called. the total variable in this method is local to it's method. So what you currently have is a method variable
You'll want to do some research into class variable. This will maintain that the instance of the object will have this variable assigned through the life cycle of the instantiated object.
When you have variables of the same name, you can get the instance variable with this keyword.
So when dealing with your setter
public void setSomething(double something) {
this.something // class variable
something // method variable
}
If you want your object to maintain state, you can set it on your object itself, and have your set deposit modify that state. Some pseudo code to get you moving forward.
public class Saving {
private double totalAmountOfDeposits; // you can modify this value with public methods
public void setDeposit(_) {
// Setter implementation
// increment totalAmountOfDeposits;
public double getTotalAmountOfDeposits(_)
// return totalAmountOfDeposits;
}
You should write a method
public void addDeposits(double deposits)
{
this.deposits = this.deposits + deposits;
}
and change setDeposits to
public void setDeposits(double deposits)
{
this.deposits = deposits;
}
after this call addDeposits to add deposits
To eliminate confusion within the Saving Class change the argument name for the setDeposits() method to double newDeposit instead of double deposits which is also a class field name. Although the construct is legal it does make it a wee bit confusing. Inside the setDeposits() method use:
this.deposit+= newDeposit;
As a matter of fact, you can get rid of the deposits field altogether since you also have the field named totalAmountOfDeposits. Use that instead:
this.totalAmountOfDeposits+= newDeposit;
You might also want a clearDeposits() method in your Saving Class:
public void clearDeposits() {
this.totalAmountOfDeposits = 0.0;
}
Your getTotalAmountOfDeposits() method within the Saving Class doesn't really make any sense either. Since you are always summing deposits anyways you can just return what is held within the totalAmountOfDeposits field:
public double getTotalAmountOfDeposits() {
return totalAmountOfDeposits;
}
The above method is would now of course be very mush the same as the getDeposits() method which could be changed to getTotalDeposits(). You can then change the getTotalAmountOfDeposits() method name to getTotalNumberOfDeposits() and add a additional class field named numberOfDeposits:
private double totalAmountOfDeposits;
private int numberOfDeposits = 0;
public double getTotalDeposits() {
return totalAmountOfDeposits;
}
public int getTotalNumberOfDeposits() {
return numberOfDeposits;
}
and in your setDeposits() method add the code line:
numberOfDeposits++;
So that it would look something like:
public void setDeposits(double newDeposit) {
totalAmountOfDeposits+= newDeposit;
numberOfDeposits++;
}
If you do add a clearDeposits() method to your Saving Class then don't forget to add the code line: numberOfDeposits = 0; into that method as well. It might now look something like:
public void clearDeposits() {
totalAmountOfDeposits = 0.0;
numberOfDeposits = 0;
}
You also have some issues within your main() method of your SavingDemo Class. Take a real close look at each call you make to the setDeposits() method for each value the User supplies. Each User supplied value goes into a specific double type variable name. Is that what you are passing to the setDeposits() method? ;)
Once you've got all that taken care of you can display to console:
System.out.println("The total amount has been deposited is " +
save.getTotalDeposits() + " by making " +
save.getTotalNumberOfDeposits() + " deposits.");

How to use integers inside of an array as parameters for a method. (Tester)

I calculate an integer and assign it into an array using a method inside a for loop, then the next method in that for loop needs the previous integer calculated as a parameter I declared it as an double which fixed that problem but now I need to print the result and I have the same problem, what do i put in the method parameters when printing because the variable was wiped after every loop in the first loop.
This is the main method class :
public class AnnualFuelTester {
public static void main(String args[]) {
//declaration of variables
int endMiles, startMiles;
double gallonsUsed, pricePerGallon;
//initialization of an array of objects
AnnualFuelUse[] fillUps = {
new AnnualFuelUse(45023, 45231, 10.00, 2.95),
new AnnualFuelUse(45231, 45480, 11.70, 2.99),
new AnnualFuelUse(45480, 45659, 9.30, 3.03),
new AnnualFuelUse(45659, 45961, 14.90, 3.05)
};
//call methods
for (int index = 0; index < fillUps.length; index++) {
double distance = fillUps[index].calcDistance();
fillUps[index].calcMPG(distance);
fillUps[index].getStartMiles();
fillUps[index].getEndMiles();
fillUps[index].getGallons();
fillUps[index].totalCost(distance);
}
//print results
System.out.printf(" %15s %15s %15s %15s %15s %15s %15s %15s %15s", "Fill Up", "Days", "Start Miles", "End Miles", "Distance", "Gallons", "Miles/Gal", "Gallons/Miles", "Price", "Total Cost\n");
for (int index = 0; index < fillUps.length; index++) {
System.out.printf("%15i %15i %15s %15s %15d %15d %15d %15d %15d", index, index, fillUps[index].getStartMiles(), fillUps[index].getEndMiles(), fillUps[index].calcDistance(), fillUps[index].getGallons(), fillUps[index].calcMPG(distance), fillUps[index].totalCost(distance), "\n");
}
}
}
This is the Class with the methods:
public class AnnualFuelUse {
//private instance variables
private int myEndMiles, myStartMiles;
private double myGallonsUsed, myPricePerGallon;
AnnualFuelUse(int sm, int em, double gu, double ppg) {
myEndMiles = em;
myStartMiles = sm;
myGallonsUsed = gu;
myPricePerGallon = ppg;
}
//distance driven
public double calcDistance() {
return myEndMiles - myStartMiles;
}
//calculate miles per gallon
public double calcMPG(double distance) {
return distance / myGallonsUsed;
}
//calculate gallons per mile
public double calcGPM(double distance) {
return (distance / myGallonsUsed) / 100;
}
//calculate total cost
public double totalCost(double distance) {
return myPricePerGallon * distance;
}
//getter start miles
public int getStartMiles() {
return myStartMiles;
}
//getter end miles
public int getEndMiles() {
return myEndMiles;
}
//getter gallons used
public double getGallons() {
return myGallonsUsed;
}
//getter price per gallon
public double getPricePerGallon() {
return myPricePerGallon;
}
}
The instructions for this program are
If you have not yet created the 8.08 Annual Fuel Use project in the Mod08
Assignments folder, please do so now.
Be sure to save a copy of these instructions in the Mod08 Documents folder.
Print a copy for your notebook.
Read the instructions carefully before you attempt the assignment.
Create two classes called
AnnualFuelUseTester and AnnualFuelUse
in the newly created project folder.
Use the fill up data you have been collecting
for your car (or the family car) and calculate
the total distance, gallons used, and cost of
gas.
Determine the minimum and maximum
values for distance, miles per gallon and
price. (Recall the Integer class constancies
MIN_VALUE and MAX_VALUE. The
Double class also has class constants of the
same name.)
Calculate annual projections for distance,
gallons used, miles per gallon, and cost
based on the data you collected.
Each fill up should be considered an object and your program design should be
based on an array of objects. Use the demo program in this lesson as a model for
how to create and process an array of objects.
If you are basically expecting the value calculated in .calcDistance() method, Have your method .calcDistance() return a value (the one you require).
Store it in a variable or directly pass that to the second called function .clacMPG()
As you are already returning a value from .calcDistance() you can do something like
int dist = fillUps[index].calcDistance();
and now you can use this dist value in any other method calls you make, like
fillUps[index].calcMPG(dist);
you can basically use one variable which will get overwritten every time the loop runs.
Use another variable:
int dist=fillUps[index].calcDistance();
//or double, depands on the method's returning value
fillUps[index].calcMPG(dist);
Assuming that AnnualFuelUse constructor arguments are: start miles (odometer), end miles, gallonsUsed and pricePerGallon.
One way to do this is returning the distance and passing as argument to the next:
int distance = fillUps[index].calcDistance();
fillUps[index].calcMPG(distance);
I can't see in your code how you are consolidating data and how you're projecting future data.
**Ok. Based on your "edit", now I know that you don't have a question, You want someone to do your homework for you!!! **

How do I call a method recursively?

I'm trying to recursively call a method until I obtain the desired output. However, I want to call a method from another class and get information from that method in order to use it in my recursive method. For example, suppose I have a parent class called Cake that contains information about a cake such as its batter(i.e. amount the batter), an extended class with a specific type of cake containing a unique instance of the batter, and I have another class called Bakery where I want to actually make cakes that are being ordered. I have a method in Bakery called createCake, and I want to recursively call this method until enough batter is in the pan to create a cake. If the amount of batter is randomly generated in the extended class, how do I call the getBatter method from that class and capture the information about the batter amount in order to use it in my recursive method for creating the cakes? Can anyone help me out with this? I'm doing something similar to this, but I don't quite understand how I would go about actually getting the information in order to get the recursion to work. I have an example of the code below, so that you can have an idea of what I'm trying to do (I know it's not very accurate). Any help would be greatly appreciated.
import java.util.Random;
public abstract class Cake
{
static Random gen = new Random(System.currentTimeMillis());
public int type; //type of cake
public static int batter = gen.nextInt() * 3; //random amount of batter
public int getType()
{
return type;
}
public int getBatter()
{
return batter;
}
}
public class RedVelvet extends Cake
{
public int type;
public int batter = gen.nextInt(3)+6; //generates between 6-8 cups of batter inclusive
public int getType()
{
return 1;
}
public int getBatter()
{
return batter;
}
}
public class Chocolate extends Cake
{
public int type;
public int batter = gen.nextInt(3)+6; //generates between 6-8 cups of batter inclusive
public int getType()
{
return 2;
}
public int getBatter()
{
return batter;
}
}
public class Pound extends Cake
{
public int type;
public int batter = gen.nextInt(3)+6;
public int getType()
{
return 3;
}
public int getBatter()
{
return batter;
}
}
public class Bakery
{
import java.util.Scanner;
System.out.print("Enter desired size of cake to be baked (Must be at least 12):");
desiredSize=scan.nextInt();
public static void createCake(int desiredSize, int currentSize) //currentSize is the current amount of batter in the pan
{
if (currentSize == desiredSize)
return;
else if (currentSize < desiredSize)
{
//Recursively call createCake method so that batter continues to be added to the pan until there is enough to make the desired cake size. I want to get the batter information from one of the extended classes in order to add it to the cake.
}
}
Is this for school or a course of sorts because I personally wouldn't go this route but then again that's my opinion. It's like, what the heck do I know about baking and I can safely tell you....absolutely nothing. Some may even say that about my programming/coding skills but then again, I'm not a programmer and I am self taught in almost all programming environments including good old Assembly most of which I have now forgotten. :/
I should think that when it comes to baking cakes (or most things for that matter) some sort of accuracy must be established so as to avoid waste and we all know that waste costs money. I'm not overly convinced that generating random amounts of cake batter is accurate enough for what you're most likely are trying to accomplish but then again, you already know this. I noticed that in your different cake classes they all basically generate a random number from 6 to 8. If they all do the same thing then why have them?
I don't believe you need recursion at all but instead a simple method called from within a loop, for example:
while (currentSize < desiredSize) {
currentSize+= getBatter(cake, desiredSize);
}
Here is how I would do this and I apologize now if you find this is all totally meaningless:
import java.util.Random;
import java.util.Scanner;
public class Bakery {
public static void main(String[] args) {
getBaking(); // :)
}
private static void getBaking(){
Scanner scan = new Scanner(System.in);
String cakeType = "";
while (cakeType.equals("")) {
System.out.print("Enter desired cake to be baked (Pound, Chocolate, "
+ "RedVelvet) or\nenter 'exit' to quit: -> ");
cakeType = scan.nextLine();
if (cakeType.isEmpty()) {
System.out.println("\nYou must supply the name of cake to bake or "
+ "enter 'exit' to quit!\n");
}
else if (cakeType.toLowerCase().equals("exit")) { System.exit(0); }
else if (!cakeType.toLowerCase().matches("(pound|chocolate|redvelvet)")) {
System.out.println("\nYou must supply the name of cake as shown above!\n");
cakeType = "";
}
}
int desiredSize = 0;
String size = "";
while (size.equals("")) {
System.out.print("\nEnter desired size of cake to be baked (must be at "
+ "least 12\"): -> ");
size = scan.nextLine();
if (size.isEmpty()) {
System.out.println("\nYou must supply the size of cake to bake or "
+ "enter 'exit' to quit!\n");
}
else if (size.toLowerCase().equals("exit")) { System.exit(0); }
else if (Integer.valueOf(size.replace("\"","")) < 12 ) {
System.out.println("\nYou must supply a cake size of 12\" or greater!\n");
size = "";
}
}
desiredSize = Integer.valueOf(size.replace("\"",""));
createCake(cakeType, desiredSize, 0);
}
public static void createCake(String cake, int desiredSize, int currentSize) {
//currentSize is the current amount of batter in the pan
while (currentSize < desiredSize) {
currentSize+= getBatter(cake, desiredSize);
System.out.println(currentSize);
}
System.exit(0); // Done! - Quit!
}
public static int getBatter(String cake, int desiredSize) {
Random gen = new Random(System.currentTimeMillis());
// Since the random generation for the batter amount is the
// same for all cake types according to your code we just
// need this:
int batterAmount = gen.nextInt(3)+6;
// But if we want to be more specific for each Cake Type
// then we can do it this way but first create the required
// batter equations for each cake type and remove the /* and
// */ from the code but first comment out (//) the batterAmount
// variable declaration above.
// NOTE: Both cake diameter AND 'Height' should play into the factor
// of how much batter is required unless of course all cakes made are
// of the same height.
/*
int batterAmount = 0;
switch (cake.toLowerCase()) {
case "pound":
batterAmount = //batter amount to make 12 inch cake + (this much batter for a 1 inch cake * (desiredSize - 12));
break;
case "chocolate":
batterAmount = //batter amount to make 12 inch cake + (this much batter for a 1 inch cake * (desiredSize - 12));
break;
case "redvelvet":
batterAmount = //batter amount to make 12 inch cake + (this much batter for a 1 inch cake * (desiredSize - 12));
break;
} */
return batterAmount;
}
}
Well, I do hope this has helped you somewhat or at least thrown a little thought into the oven :P

Categories

Resources