Pizza Ordering Program - java

public class PizzaEx {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
char letter;
String input;
int sizeD;
int pizzaCount=1;
Pizza pieOne;
do{
sizeD = getValidSize();
input = JOptionPane.showInputDialog(null, "What type of topping do you wish to order? " +
"\n Green Pepper" +
"\n Mushroom"+
"\n Sausage"+
"\n Pepperoni"+
"\n Plain");
pieOne = new Pizza(sizeD, input);
System.out.println(pieOne);
System.out.println("The Number of pizzas made are " + pieOne.getPizzaCount() +"."+"\n");
input = JOptionPane.showInputDialog(null, "Do you wish to continue?\n "+
"'y' or 'Y' for YES\n"+
"'n' or 'N' for NO\n");
letter = input.charAt(0);
pizzaCount = pizzaCount +1;
}
while (letter == 'Y'|| letter == 'y');
System.exit(0);
}
private static int getValidSize()
{
int d;
String input;
do{
input = JOptionPane.showInputDialog(null, "What size of pizza do you wish to order? "+
"\n 9 inch"+
"\n 12 inch"+
"\n 16 inch");
d = Integer.parseInt(input);
} while (!(d==9 || d==12 || d==16));
return d;
}
so the above is my main class
public class Pizza {
private int diameter;
private int numOfPizza;
private double price;
private String tops;
Pizza(int sizeD, String input) {
diameter = sizeD;
tops = input;
}
public int getDiameter(){
return diameter;
}
/**
*
* #param pizzaCount
* #return
*/
public int getPizzaCount(){
return numOfPizza;
}
public double getPrice(){
return price;
}
public String getToppings(){
return tops;
}
public void setDiameter(int sizeD){
if (sizeD == 9)
diameter = 9;
else if ( sizeD == 12)
diameter = 12;
else if (sizeD == 15)
diameter = 15;
else
diameter = 0;
}
public void setPizzaCount(int pizzaCount){
numOfPizza = pizzaCount;
}
public void setPrice(double total){
price = total;
}
public void setToppings(String input){
if ("green pepper".equalsIgnoreCase(input))
tops = "Green Pepper";
else if ("mushroom".equalsIgnoreCase(input))
tops = "Mushroom";
else if ("sausage".equalsIgnoreCase(input))
tops = "Sausage";
else if ("pepperoni".equalsIgnoreCase(input))
tops = "Pepperoni";
else
tops = "Plain";
}
private double calculatePrice(int sizeD, String input){
double total;
if (sizeD == 9 && (tops).equalsIgnoreCase("plain"))
total = 5.95;
else if (sizeD == 9)
total = 6.95;
else if (sizeD == 12 && (tops).equalsIgnoreCase("plain") )
total = 7.95;
else if (sizeD == 12)
total = 8.95;
else if (sizeD == 16 && (tops).equalsIgnoreCase("plain"))
total = 9.95;
else if (sizeD == 16)
total = 10.95;
else
total = 0.0;
return total;
}
public String toString(){
String pizzaString ="You have ordered a "+diameter + " inch pizza with "+tops +" toppings and a price of $"+ calculatePrice(diameter, tops);
return pizzaString;
}
When I do the the print out, it keeps saying amount of pizza made are = 0 even though I set pizzaCount = 1. Also when it ask for topping, if I type any String besides the valid topping choices {"green peppers", "mushroom", "sausage", "pepperoni", "plain"} it will count the String as a topping and will be charged for the topping when it should be anything that is not {"green peppers", "mushroom", "sausage", "pepperoni"} should be considered "plain"
This is not a homework assignment or test problem. It was some extra practice handed out by my professor and is not for a grade. I just want some help to clarify why the String tops is not being assigned the value that the method setToppings() is calling to do.

The reason why you always get 0 with getNumOfPizza() is because you never increment int numOfPizza, you only increment pizzaCount in main.
As for the topping, the reason why you charge for toppings even if you enter an invalid String, is because of your logic in calculatePrice, where you charge for topping if !equalsIgnoreCase("plain"). In other words, anything except for "plain" will be considered a topping. In fact, the logic in this method is unnecessarily convoluted, I suggest you simplify some of the if statements:
private double calculatePrice(int sizeD, String input){
if(!(tops).equalsIgnoreCase("plain")) {
total = 1;
} else {
total = 0;
}
if(sizeD == 9) {
total += 5.95;
}
else if(sizeD == 12) {
total += 7.95;
}
else if(sizeD == 16) {
total += 9.95;
}
return total;
}

Your class Pizza has a field private int numOfPizza; which you are accessing with pieOne.getPizzaCount(). Because that field hasn't been initialized (and it is a primitive int) it has a default value of 0. One possible fix,
private int numOfPizza = 1;
Be sure that you are considering which count you are interested in; the local count or the Pizza count. Once that is fixed, you should also change
pizzaCount = pizzaCount +1;
to something like
pizzaCount += pieOne.getPizzaCount();

You have the following constructor:
Pizza(int sizeD, String input) {
diameter = sizeD;
tops = input;
}
As you can see it does not run your logic from setToppings.
It also does not set numOfPizza and you do not call your setPizzaCount() method either. So this class variable remains 0

You seem to have two different fields to hold the number of pizzas. The pizza class should only hold data about the individual pizzas and the other class should hold the data about the amount of pizzas. In your main class you initialize pizzaCount to 1, but then try getting the number from the pizza numOfPizza field.
Edit Also, on a separate note, your main class has too much going on in there. You should abstract some stuff out and put it in methods.

When you print:
System.out.println("The Number of pizzas made are " + pieOne.getPizzaCount() +"."+"\n");
you are accessing pieOne. Lets check initialization:
Pizza pieOne = new Pizza(sizeD, input);
where sizeD stores the pizza size (like 9) and input stores a String.
The function pieOne.getPizzaCount() checks inside pieOne and returns numOfPizza;
public int getPizzaCount(){
return numOfPizza;
}
But since you never actually stored that value inside the object, it will return zero!
You net to call setPizzaCount() before printing anything.
Hope it helps.

The reason the String for toppings is coming back as whatever the user types every time is because the setToppings() method is declared but never called. You need to call it on the "tops" variable for it to work. As it is, the program skips the method altogether.
Here is one way you could call the method in your program:
public String toString()
{
//method call
setToppings(tops);
String pizzaString = "You have ordered a " + diameter + " inch pizza with " + tops + " toppings and a price of $" + calculatePrice(diameter, tops);
return pizzaString;
}
}
The problem with your number of pizzas is the same situation. The setPizzaCount() method had never been called, therefore numOfPizza was never set. Since int variables automatically default to 0 if they are not instantiated, you get a value of 0 every time. Also, you may want to consider using the increment (++) operator when you add one to the number of pizzas. It exists to help make your code easier for you to write and for others to understand when incrementing numbers.
Here's an example:
do
{
sizeD = getValidSize();
input = JOptionPane.showInputDialog(null, "What type of topping do you wish to order? " +
"\n Green Pepper" +
"\n Mushroom" +
"\n Sausage" +
"\n Pepperoni" +
"\n Plain");
pieOne = new Pizza(sizeD, input);
//method call
pieOne.setPizzaCount(pizzaCount);
System.out.println(pieOne);
System.out.println("The Number of pizzas made are " + pieOne.getPizzaCount() + "." + "\n");
input = JOptionPane.showInputDialog(null, "Do you wish to continue?\n " +
"'y' or 'Y' for YES\n" +
"'n' or 'N' for NO\n");
letter = input.charAt(0);
pizzaCount++;
}

Related

Having trouble with Java Scanner input and a while loop, with multiple if statements in it [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 3 years ago.
I wish to limit the input of an integer value, between certain values using a while loop, with a couple of if-else if-else statements inside it! It's kinda working, but not exactly as it should... thought of using a switch as well, but I'm too "green" to know how! If someone's up for it and knows how... I'd welcome the use of a switch as well! Even a nested switch if need be...
Here's my code:
public class OOPProject {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner sc = new Scanner(System.in);
Car Honda = new Car(2018, 20000, "Honda", "Civic", 200, 6, 0, 0);
System.out.println("Manufacturer is: " + Honda.maker + ", model: " + Honda.model +
", year of fabrication: " + Honda.year + ", price: " + Honda.price + "!");
System.out.println("Please start the engine of your vehicle, by typing in 'Yes' or 'Start' or 'Turn on'!");
System.out.print("Do you wish to start the engine?");
System.out.println(" ");
Honda.StartEngine(sc);
//System.out.println("Engine is on!");
System.out.println("Do you wish to depart? Shift in to the first gear then and accelerate!");
System.out.println("Type in the speed: ");
Honda.accelerate(sc);
System.out.println("We are departing! Shifting in to " + Honda.currentGear +
"st gear and accelerating to " + Honda.currentSpeed + " km per hour!");
}
Constructor & functions:
public class Car {
public int year;
public int price;
public String maker;
public String model;
public int maximumSpeed;
public int numberOfGears;
public int currentSpeed;
public int currentGear;
public boolean isEngineOn;
public Car(int year, int price, String maker, String model, int maximumSpeed,
int numberOfGears, int currentSpeed, int currentGear) {
this.year = year;
this.price = price;
this.maker = maker;
this.model = model;
this.maximumSpeed = maximumSpeed;
this.numberOfGears = numberOfGears;
this.currentSpeed = currentSpeed;
this.currentGear = currentGear;
}
public String StartEngine(Scanner in) {
while(in.hasNext()) {
String input = in.nextLine();
if(input.equals("Yes") || input.equals("Start") || input.equals("Turn on")) {
isEngineOn = true;
System.out.println("Engine is on!");
return input;
} else {
System.out.println("Your input is not correct! Please start the engine!");
}
}
return null;
}
public int accelerate(Scanner in){
while(in.hasNextInt()){
currentSpeed = in.nextInt();
if(isEngineOn && currentSpeed > 0){
currentGear++;
} else if(currentSpeed > 50){
System.out.println("We cannot accelerate to more than 50 km per hour, when shifting in the 1st gear!");
} else{
System.out.println("We cannot depart at 0 km per hour!");
}
}
return 0;
}
}
It's taking the input, but it's not going further with it as it should, neither does it give an error message or stop the app, what's my mistake?
Changing the order of your if statement will work.
In your current method:
if(isEngineOn && currentSpeed > 0)
Will always return true with any value that you enter.
Using this method will get you a little further, although I suspect it will still won't be what you are expecting, but I hope it helps you in the right direction.
public int accelerate(Scanner in){
while(in.hasNextInt()){
currentSpeed = in.nextInt();
if(currentSpeed > 50 && currentGear <= 1){
System.out.println("We cannot accelerate to more than 50 km per hour, when shifting in the 1st gear!");
} else if(isEngineOn && currentSpeed > 0){
currentGear++;
break; /* I've added this to break out of the method to progress in your flow */
} else{
System.out.println("We cannot depart at 0 km per hour!");
}
}
return 0;
}
}

How to write toString() and equals() methods?

I'm trying to make this piece of code print the actual numbers, and not the hexadecimal location.
public class MoneyDriver
{
//This is a driver for testing the class
public static void main(String[] args)
{
final int BEGINNING = 500;
final Money FIRST_AMOUNT = new Money(10.02);
final Money SECOND_AMOUNT = new Money(10.02);
final Money THIRD_AMOUNT = new Money(10.88);
Money balance = new Money(BEGINNING);
System.out.println("The current amount is " +
balance.toString());
balance = balance.add(SECOND_AMOUNT);
System.out.println("Adding " + SECOND_AMOUNT +
" gives " + balance.toString());
balance = balance.subtract(THIRD_AMOUNT);
System.out.println("Subtracting " + THIRD_AMOUNT +
" gives " + balance.toString());
boolean equal = SECOND_AMOUNT.equals(FIRST_AMOUNT);
if(equal)
System.out.println(SECOND_AMOUNT + " equals "
+ FIRST_AMOUNT);
else
System.out.println(SECOND_AMOUNT.toString() +
" does not equal " + FIRST_AMOUNT);
equal = THIRD_AMOUNT.equals(FIRST_AMOUNT);
if(equal)
System.out.println(THIRD_AMOUNT + " equals " +
FIRST_AMOUNT);
else
System.out.println(THIRD_AMOUNT + " does not equal "
+ FIRST_AMOUNT);
}
}
This is the main class which is called by moneydriver
public class Money
{
private long dollars;
private long cents;
public Money(double amount)
{
if (amount < 0)
{
System.out.println(
"Error: Negative amounts of money are not allowed.");
System.exit(0);
}
else
{
long allCents = Math.round(amount*100);
dollars = allCents/100;
cents = allCents%100;
}
}
public Money add(Money otherAmount)
{
Money sum = new Money(0);
sum.cents = this.cents + otherAmount.cents;
long carryDollars = sum.cents/100;
sum.cents = sum.cents%100;
sum.dollars = this.dollars
+ otherAmount.dollars + carryDollars;
return sum;
}
public Money subtract (Money amount)
{
Money difference = new Money(0);
if (this.cents < amount.cents)
{
this.dollars = this.dollars - 1;
this.cents = this.cents + 100;
}
difference.dollars = this.dollars - amount.dollars;
difference.cents = this.cents - amount.cents;
return difference;
}
public int compareTo(Money amount)
{
int value;
if(this.dollars < amount.dollars)
{
value = -1;
}
else if (this.dollars > amount.dollars)
{
value = 1;
}
else if (this.cents < amount.cents)
{
value = -1;
}
else if (this.cents > amount.cents)
{
value = 1;
}
else
{
value = 0;
}
return value;
}
}
The objectives is to write equals method (on main class). The method compares the instance variables of the calling object with instance variables of the parameter object for equality and returns true if the dollars and the cents of the calling object are the same as the dollars and the cents of the parameter object. Otherwise, it returns false.
Write toString method (on main class). This method will return a String that
looks like money, including the dollar sign. Remember that if you have less than 10 cents, you will need to put a 0 before printing the cents so that it appears correctly with 2 decimal places.
If both of the method is implemented correctly
According to tutorialspoint, you're supposed to do either
String toString()
static String toString(int i)
But the supplied moneydriver already has the tostring method, but doesn't display the numbers, instead it displays a hexadecimal location of the variable.
The equals method is already used in moneydriver, so I'm kinda lost on that too.
The correct output should look like this
The current amount is $500.00
Adding $10.02 gives $510.02 Subtracting $10.88 gives $499.1
$10.02 equals $10.02
$10.88 does not equal $10.02
Completely lost in this, thanks in advance for help.
To get a String output on the Money class, do something akin to:
public class Money
{
private long dollars;
private long cents;
// suggested approach for constructor
public Money(long amount) throws IllegalArgumentException
{
if (amount < 0) {
throw new IllegalArgumentException("Amount may not be less than 0");
}
// do other stuff
}
...
public String toString()
{
return String.format("%d.%02d", dollars, cents);
}
public boolean equals(Object obj)
{
boolean equal = false;
if (obj instanceof Money) {
Money chk = (Money)obj;
equal = (chk.dollars == this.dollars &&
chk.cents == this.cents);
}
return equal;
}
} // end class Money

Error: Cannot find symbol when passing and returning variables

Rookie mistake?
Hello, I'm a first-year computer science student and I keep getting cannot find symbol errors. I declared the variable in the main method, passed it to another method, modified it, and then returned it. For some reason, the compiler cannot find the symbols result, input, and points. I'm sure it's the same reason for all of them. Any help would be appreciated.
public class Fishing
{
public static void main(String[] args)
{
do
{
String input; //Holds user input
int points; // Holds player's points
int score = 0; // Sets player's score to 0
final int DIE_SIDES = 6; // # of sides for the die
//Create an instance of the Die class
Die die = new Die(DIE_SIDES);
//Roll the die once and store value in result
die.roll();
int result = die.getValue();
getScore(points, result);
String input = getInput();
//Keeps running total of player's score
score = score + points;
} while (input == "yes");
System.out.print(0);
}
/**
The getScore method will calculate the player's score
depending on what the player rolled. It will also show
a message and return the score.
#return A reference to an integer object containing
the player's score for one roll.
*/
public static int getScore(int points, int result)
{
if (result == 1)
{
JOptionPane.showMessageDialog(null, "Waaaaahhhhh, you have caught " +
"a shark. Sharks are dangerous. You " +
"have been awarded zero points.");
points = 0;
return points;
}
else if (result == 2)
{
JOptionPane.showMessageDialog(null, "You have caught a jellyfish. " +
"This beautiful creature has awarded you " +
"50 points!!");
points = 50;
return points;
}
else if (result == 3)
{
JOptionPane.showMessageDialog(null, "You have caught an old boot. " +
"Maybe you can sell this old boot after it " +
"dries out. You have been awarded 1 point.");
points = 1;
return points;
}
else if (result == 4)
{
JOptionPane.showMessageDialog(null, "You have caught an Alaskan salmon. " +
"This delicious and popular fish has awarded you " +
"75 points!!!");
points = 75;
return points;
}
else if (result == 5)
{
JOptionPane.showMessageDialog(null, "You have caught a small fish. You " +
"have been awarded 20 points!");
points = 20;
return points;
}
else
{
JOptionPane.showMessageDialog(null, "You have caught a treasure chest!! " +
"It is filled with shining pieces of gold, and " +
"you have been awarded 100 points!!!!");
points = 100;
return points;
}
}
/**
The getInput method will receive the user's input
and return it to the main method.
#return A reference to a String input value containing
the user's response.
*/
public static String getInput()
{
//Prompt user to enter response
response = JOptionPane.showInputDialog("Would you like to play another " +
"round of fishing? Enter yes or no.");
return response;
}
}
We need to make the following changes:
Result is declared in main() method and hence, it is local to main() only. getScore has no knowledge of it. If we want to access result, input and points in getScore() method then we need to pass all of them to getScore().
getInput() returns an input. So, we don't need to pass any argument to it. We can change getInput(String response) to getInput() and modify main() so that value returned by getInput() is assigned to input variable (input = getInput();)
Here are some basics of parameter passing in java. I would recommend going through it.

I don't know why the variables are not initializing, all variables declared inside if statements aren't recognized

I can't figure out why the variables aren't being able to be printed
import java.text.*;
import java.io.*;
public class CoffeeBags
{
//CONSTANTS
public static final double SINGLE_PRICE = 5.5;
public static void main( String[]args)
throws IOException
{
BufferedReader br =new BufferedReader(new InputStreamReader(System.in));
//Display Message "Enter Number of Bags Ordered: "
System.out.print("Enter Number of Bags Ordered: ");
//Save input as string
String inputStr = br.readLine();
//Verify that input is integer
int numBags = Integer.parseInt(inputStr);
//Make sure number is above 0
if (numBags <= 0)
System.out.print("Please purchase at least one bag.");
if (numBags <= 0)
System.exit(0);
//Calculate purchase price
double purchasePrice = SINGLE_PRICE * numBags;
//Set numBagsLeft to numBags
int numBagsLeft = numBags;
//Determine Number of Large Boxes needed
if (numBagsLeft >= 20) {
int largeBoxCount = numBagsLeft / 20;
}
//Reinitialize Number of Bags to the remainder
int numBagsLeft2 = numBagsLeft % 20;
if (numBagsLeft2 >= 10) {
int mediumBoxCount = numBagsLeft2 / 10;
};
int numBagsLeft3 = numBagsLeft2 % 10;
if (numBagsLeft3 > 0 && numBagsLeft3 <= 5){
int smallBoxCount = 1;
} else {
int smallBoxCount = 2;
}
//Display
System.out.print("\n\nNumber of Bags ordered: " + numBags + " - " + purchasePrice
+ "\nBoxesUsed: "
+ "\n "+largeBoxCount+" Large - $+largeBoxCount*1.80
+ "\n "+mediumBoxCount+" Medium - $"+mediumBoxCount*1.00
+ "\n "+smallBoxCount+" Small - $"+smallBoxCount*.60
+ "\n\nYour total cost is: $"+largeBoxCount*1.80+mediumBoxCount*1.00+smallBoxCount*.60+purchasePrice;;)
}
}
Okay. So the code is supposed to take in a number of "Coffee Bags", and then, using a system of if statements, filter down through in order to find out how many boxes you will need to purchase in order to best save money. The problem I'm having is that the variables such as largeBoxCount and mediumBoxCount are not being initialized, and thus aren't able to be called when I go to print them.
I see some scoping issues. Variables declared inside of an if block are visible only inside the if block and not outside of it. Declare those variables before the if blocks and in the main method.
bar = 0; // declared before the if block, visible inside and out
if (foo) {
bar = 1; // this variable is visible outside of the if block
int baz = 1; // this variable is not visible outside of the if block
}
System.out.println("bar = " + bar); // legal
System.out.println("baz = " + baz); // illegal
You are declaring the variables inside the if statements, when the scope ends they are removed.

Move a method to another method java

import java.util.Scanner;
public class Hw4Part4 {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
//Ask for the diners’ satisfaction level using these ratings: 1 = Totally satisfied, 2 = Satisfied,
//3 = Dissatisfied.
System.out.println("Satisfacion leve: ");
int satisfactionNumber= sc.nextInt();
//Ask for the bill subtotal (not including the tip)
System.out.println("What is the bill subtotal: ");
double subtotal= sc.nextInt();
//Report the satisfaction level and bill total.
System.out.println("The satisfaction level is: "+ satisfactionLevel(satisfactionNumber));
System.out.println("The bill total is: " + getBillTotal(tipPercentage, subtotal));
}
public static String satisfactionLevel(int satisfactionNumber){
String satisfactionL = "";
if (satisfactionNumber == 1){
satisfactionL ="Totally-satisfied";
}
if (satisfactionNumber == 2){
satisfactionL = "Satisfied";
}
if (satisfactionNumber == 3){
satisfactionL = "Dissatisfied";
}
return satisfactionL;
}
//This method takes the satisfaction number and returns the percentage of tip to be
//calculated based on the number.
//This method will return a value of 0.20, 0.15, or 0.10
public static double getPercentage(int satisfactionNumber){
double getPercentage = 0;
if (satisfactionNumber ==1){
getPercentage = 0.20;
}
if (satisfactionNumber ==2){
getPercentage = 0.15;
}
if (satisfactionNumber ==3){
getPercentage = 0.10;
}
return getPercentage;
}
public static double getBillTotal(double tipPercentage, double subtotal){
double totalWithTip= (subtotal + ( getPercentage(satisfactionNumber) * subtotal));
return totalWithTip;
}
}
I am having issues on the last method, the whole code is shown above.
It says there is error with the part where I am trying to use the previous method.
I need to get the percentage which was computed on the previous method.
At this part of the code:
public static double getBillTotal(double tipPercentage, double subtotal){
double totalWithTip= (subtotal + ( getPercentage(satisfactionNumber) * subtotal));
return totalWithTip;
}
You call this method:
getPercentage(satisfactionNumber)
However, this variable:
satisfactionNumber
Doesn't exist in this method's scope. You should pass this variable to the method as so:
public static double getBillTotal(double tipPercentage, double subtotal, int satisfactionNumber){
double totalWithTip= (subtotal + ( getPercentage(satisfactionNumber) * subtotal));
return totalWithTip;
}
So when you call the method in the main, you pass it in:
System.out.println("The bill total is: " + getBillTotal(tipPercentage, subtotal, satisfactionNumber));
tipPercentage cannot be resolved to a varible
Pretty much any variable you pass in, you must create. So when you do the above line, make sure you have all variables delcared:
double tipPercentage, subtotal, satisfactionNumber;
//now set these three variables with a value before passing it to the method
System.out.println("The bill total is: " + getBillTotal(tipPercentage, subtotal, satisfactionNumber));
It's hard to tell, but I think you need to remove whitespace:
double totalWithTip = subtotal + (getPercentage(satisfactionNumber) * subtotal);
return totalWithTip;
This code assumes a variable:
int satisfactionNumber;
and a method:
double getPercentage(int satisfactionNumber) {
// some impl
}

Categories

Resources