Pizza price calculating using 'if' statements in java [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 3 years ago.
I've tried to make Java code to communicate with the user.
The code is about calculating a pizza price assuming the pizza price is a final int and doesn't change.
The only thing that affects the price is the add-on that the customer wants on the pizza (tomato, mushrooms, cheddar cheese).
I've tried to create code that covers every option the customer picks using 'if' statements,
but I think there is easier way to do it.
(I want the program to calculate the price given only the add-on name.)
For example, the customer picks Mushroom and Tomato so the pizza price will be the pizza price + tomato price + mushroom price.
Is there any easier way to solve it?
Or should I cover every option the customer picks with if/else statements?
public static void main(String[] args){
Scanner s= new Scanner(System.in);
final int pizzaPrice= 12;
int Mushrooms = 2;
int Tomato= 2;
int Corn = 2;
int Olives = 2;
int CheddarCheese=3;
int bulgaritCheese=3;
int yellowCheese= 3;
String cheapAddOns ="Mushrooms , Tomato, Corn, Olives";
String expensiveAddOns = "Cheddar cheese , Bulgarit cheese , Yellow cheese";
System.out.println("Please enter first AddOns(Mushrooms , Tomato , Corn, Olives): ");
cheapAddOns=s.next();
System.out.println("Please enter second AddOns (Cheddar cheese , Bulgarit cheese ,Yellow cheese)");
expensiveAddOns=s.next();
if( cheapAddOns== "Mushrooms" || expensiveAddOns=="Cheddar cheese" ) {
System.out.println("Your Pizza price is: $" + pizzaPrice + Mushrooms + CheddarCheese );
}
else if (cheapAddOns=="Tomato" || expensiveAddOns=="Bulgarit cheese") {
System.out.println("Your Pizza price is: $" +pizzaPrice+ Tomato + bulgaritCheese);
}
}

First of all when you name your variables, don't start with a capital letter
int mushrooms, not int Mushrooms.
Second thing, when you compare Strings == operator will not work. you must use stringName.equals(). In your case it would look like:
cheapAddOns = s.next();
if(cheapAddOns.equals("tomato") || cheapAddOns.equals("mushrooms") || ...){
//this way you can get one if for all cheap addons;
pizzaPrice += 2; //read below to undrstand why i would add price this way
}
And the same check for expensive addons.
What you do when you initiate cheapAddOns and expensiveAddOns is incorrect, I mean that you initiate them with start variable, and next you read them from standard input. Initiate them with no value:
String cheapAddOns;
String expensiveAddOns;
And for this example, you dont have to use final int, better initiate it as an normal integer, and if any statment is true, add to this value. It would look like this:
int pizzaPrice = 12;
int cheapAddonPrice = 2;
int expensiveAddonPrice = 3;
if(anyStatement){
pizzaPrice += 2; //2 for cheap, 3 for expensiv addon
}
System.out.println("Your pizza costs: $" + pizzaPrice)
It works only when all cheap addons cost $2 and all expensive addons cost $3. If each addon has another price, you will need more if statements to calculate price.
But calculate price in as many statements as you want and print it once (until you print only price (without addons list).
You made a lot of simple mistakes here so i think that you just start your programming adventure. Don't learn bad habbits, try to imporove your code with each day.

if all cheap add-ons have the same price, one way could be:
String cheapAddOns = "Mushrooms, Tomato, ...";
int cheapPrices = 2;
System.out.println("Please enter first AddOns(Mushrooms , Tomato , Corn, Olives): ");
String cheap = s.next();
int price = pizzaPrice;
if ( cheapAddOns.indexOf(cheap) >= 0 ) {
price += cheapPrice;
}
then repeat the code using expensiveAddOns.
Note that you will need to consume the CR before calling s.next() to get the user's next input.

Related

Program getting stuck in while loop?

I need to write a program that calculates beverages for an entered amount of money. It was working before but I don't know if NetBeans just got tired of doing stuff or what because it suddenly couldn't get past the inputs. I can't figure out what I need to change to get it to function properly again and I can only assume it's the while loop that it's getting stuck on.
I have tried changing numbers, deleting spaces, altering the while conditions, moving line breaks around, and nothing works. Here is the official question:
Johnny is at the bar and he is going to drink beer.
Write a program that computes how many beers he can buy for money that he has. The program reads the amount and the price of beer, and prints how many beers he can afford. Consider also tax (10%) and tips (20%). Print the result in the following form: If a beer costs $3.25, Johnny can have 3 beers for $15 (he will pay $12.87).
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double br;
double amt;
double taxPrc;
double bill;
int count = 0;
System.out.printf("enter ur name: ");
String name = sc.nextLine();
System.out.printf("Enter price of beverage: $");
br = sc.nextDouble();
System.out.printf("Enter amt %s has: $", name);
amt = sc.nextDouble();
taxPrc = br * 1.1;
bill = taxPrc * 1.2;
while(bill<amt) {
count++;
bill = taxPrc * 1.2;
}
System.out.printf("if bevergae costs $"+br+", "+name+" can have "+count+" beverges for $"+amt+" (the bill will be $"+bill+").");
System.out.println();
}
My editor isn't showing that there are any problems. The file runs:
"enter ur name (name), Enter price of beverage $(#), Enter amt (name) has $(input number)"
then it just stops showing anything and leaves me on a blank until I stop it.
It's supposed to go on "if beverage costs $X, [name] can have [#] beverages for $[#] (the bill will be $[#])."
I was having an issues trying to get it to display the correct number for the bill less than the initial amount entered when it stopped working.
Just think about this block of code on its own for a bit
bill = taxPrc * 1.2;
while(bill<amt) {
count++;
bill = taxPrc * 1.2;
}
?
What in the while loop changes either bill or amt? Remember, a while loop runs until something in its conditional statement (in this case bill<amt) changes. As nothing in the while loop changes anything in the condition statement, it runs forever.
Your code doesn't change amt at all and just keeps resetting bill to the same value.

How to correlate an assigned String value to an Integer value?

I'm writing a code that allows the user to dictate what type of investment they want (Annual, Monthly or Quarterly) and each investment type correlates to a specific integer: i.e. Annual = 1, Monthly = 12, and Quarterly = 4. However when I assigned annual a value, I also need it to correlate to an int value in my investment equation below and am completely stumped on how to do so.
import java.util.Scanner;
import java.lang.Math;
public class CompoundInterest {
public static void main (String [] args)
{
Scanner cool = new Scanner (System.in);
double saving, rate;
int principal, years;
int choice;
System.out.println("Please enter you principal investment:");
/*Print statment prompts user to enter their principal investment*/
principal = cool.nextInt();
System.out.println("Would you like to have a regular investment plan?");
/* Print out statement asks user if they would like to participate in a regular investment plan*/
String question =cool.next();
System.out.println("What type of investment plan would you prefer (Annual, Quarterly, or Monthly)?");
String quest =cool.next();
while (quest.equalsIgnoreCase(("Annual")))
{ String Annual="1";
Annual.equals(choice);
}
System.out.println("Please enter the number of years that you wish to invest for:");
/* Print statement prompts user to enter the number of years that they wish to invest for*/
years = cool.nextInt();
System.out.println("Please enter the return rate per year:");
/* Print statement prompts user to enter the return rate per year*/
rate = cool.nextDouble();
saving = principal*(1+(rate/choice))* Math.pow(choice, years);
System.out.printf("%.2f", saving);
}
Once the type of investment plan is answered, you need to check if the quest variable matches any of the string you are expecting, i.e., Annual, Quarterly, or Monthly.
If the quest matches any of the choices, you assign a correct value to the choice variable, i.e., 1, 4, or 12.
You also may also need to think of situations if the answer doesn't match any of the correct choices.
if ("Annual".equalsIgnoreCase(quest)) {
choice = 1;
} else if ("Quarterly".equalsIgnoreCase(quest)) {
choice = 4;
} else if ("Monthly".equalsIgnoreCase(quest)) {
choice = 12;
} else {
//you need to do something here.
}
I would recommend using an enum that defines the int you want. I'll call the enum Plan and the int term:
public enum Plan {
ANNUAL(1),
QUARTERLY(4),
MONTHLY(12);
int term;
Plan(int term) {
this.term = term;
}
};
You would use this in your code like this (this replaces int choice):
Plan plan = Plan.valueOf(quest.toUpperCase());
saving = principal * (1 + (rate / plan.term)) * Math.pow(plan.term, years);
I think you are going to need different versions of your calculation. The enum approach would support this easily if you added a method to the enum that switches on the value of the enum. You can work out the different implementations of the calculation and define them in the case statements.
double calculateSavings(int principal, double rate, int years) {
switch (this) {
case ANNUAL:
case QUARTERLY:
case MONTHLY:
default:
return principal * (1 + (rate / term)) * Math.pow(term, years);
}
}
If you go this route you would use it in your code like this:
// saving = principal * (1 + (rate / plan.term)) * Math.pow(plan.term, years);
saving = plan.calculateSavings(principal, rate,years);

Can't understand this scanner or addition command

I'm very new to Java and don't quite understand it all fully, I'm working on a Uni workshop assignment but am having trouble with this particular question.
"Write a program that asks the user to enter how many minutes they have used, and how many texts they have used.
Both inputs should be whole numbers (integers).
The program should then calculate the user’s mobile phone bill, assuming that texts cost 7p and calls 12p.
Should display price of calls, texts and the total bill, both figures added together"
Scanner userInput = new Scanner(System.in);
System.out.println("How many minutes have you used?");
String one = userInput.nextLine();
System.out.println("How many texts have you used?");
String two = userInput.nextLine();
int a = 12;
int b = 7;
System.out.println("The total cost of your minutes is "+one);
System.out.println("The total cost of you texts is "+two);
System.out.println("The total cost of your phone bill is "+one + two);
I have the basic part to the question figured out, but can't figure out why I can't add to the code for it to figure out the price, being 12 p for minutes, and 7p for texts. As well as this I can't get the total cost of the phone bill to add together correctly. I did earlier and I know it's very easy, but I've completely forgotten how to do it.
I know I need to be able to understand a scanner better, but I did the previous tasks easy enough but this has really stumped me tbh. Do I need to rename the scanner, but when I change the name of the integer line to something like "totalCostOfTexts/Minutes etc" it either says it has already been defined, or is missing some kind of symbol.
Any feedback is appreciated.
I add the code :
int = userInput = minutes * 12:
As that's what is used in the previous part of a similar question, but all the feedback I get is that it is not a statement, so it can't process. I'm really struggling with this tbh.
Following code will work for you
Scanner userInput = new Scanner(System.in);
System.out.println("How many minutes have you used?");
int one = userInput.nextInt();
System.out.println("How many texts have you used?");
int two = userInput.nextInt();
int a = 12; //don't use such variable names
int b = 7;
int minute_bill=12*a; //see the variable,will make things easier to review
int text_bill=7*b;
int result=minute_bill+text_bill;
System.out.println("The total cost of your minutes is "+minute_bill);
System.out.println("The total cost of you texts is "+ text_bill);
System.out.println("The total cost of your phone bill is "+result);
and also
You can use Scanner's nextInt() method for taking integer input
from console.
Don't use such variable names like a,b etc. define them according to the attribute whose value you are storing in them (see above minute_bill and text_bill are making the code clean and easy to review)
And if you are bound to get String value from console,but want to convert entered value to Integer later on, then you can do it like following code
String mystring=userInput.nextLine(); //userInput is user Scanner's object
int num=Integer.parseInt(mystring);
I think this is what you want to do...
Scanner userInput = new Scanner(System.in);
System.out.println("How many minutes have you used?");
int one = Integer.valueOf(userInput.nextLine());
System.out.println("How many texts have you used?");
int two= Integer.valueOf(userInput.nextLine());
int a = 12;
int b = 7;
System.out.println("The total cost of your minutes is "+ (one * 12);
System.out.println("The total cost of you texts is "+ (two * 7));
System.out.println("The total cost of your phone bill is "+ ((one * 12) + (two * 7));

Reducing duplication in code

I currently have multiple code like this for different toppings
// Toppings - Egg
System.out.print("Do you want " + egg.getType() + "?");
input = keyboard.nextLine();
choice = input.charAt(0);
if (choice == 'y') {
l.add(egg.getType());
c.add((double) egg.getCost());
numberOfToppings = numberOfToppings + 1;
totalToppingPrice = totalToppingPrice + egg.getCost();
toppings = toppings + "Egg";
}
It works fine, however i was hoping i could do all toppings in just one block of code. Because i've got around 5 of these, and it takes up far too much, and i've been advised to do so. Anyone got any ideas for how this could be done ? thanks
All the toppings should be gathered together in an enumeration, as long as the topping set is closed and cannot change during the program execution.
enum Topping{
EGG("egg", 22),... ;
private String type;
private double cost;
private Topping(String type, double cost){
this.type = type;
this.cost = cost;
}
//getters and setters
}
Then, you could write a method inside your class containing your code above that should be able to handle a Topping instance, like this:
private handleTopping(Topping top){
System.out.print("Do you want "+top.getType() +"?");
input = keyboard.nextLine();
choice = input.charAt(0);
if (choice == 'y'){
l.add(top.getType());
c.add(top.getCost());
numberOfToppings = numberOfToppings + 1;
totalToppingPrice = totalToppingPrice + top.getCost();
toppings = toppings + " " + top.getType();
}
}
Finally, call the method for all toppings available
for(Topping top : topping.values()){
handleTopping(top);
}
It's all about the DRY (don't repeat yourself principle). It's not even necessarily tied to the object oriented paradigm. Even in procedural programming, one of the core principles is to extract common and frequently used functionalities to parameterized procedures.
I would suggest you make a Topping class that you can use as follows:
Toppping egg = new Topping ("egg", 0.5); // Cost
ArrayList<Topping> toppings = new ArrayList<Topping>();
toppings.add(egg);
Later you can loop over the toppings vector similar to this:
for (Topping current : toppings) {
if (wantsTopping(current)) {
chosenToppings.addObject(current);
}
}
Note: This is Java like code, but it won't compile. There are still some things you need to look up

How to obtain and utilize next String in Java

I have been fighting with this for quite some time and have found a couple useful resources, yet the problem persists.
Here's my code:
import java.util.Scanner;
public class Stocks {
public static void main(String [] args){
// value of stock at beginning of year and end of year.
final int beginningStock = 10;
final int endStock = 20;
// value of stocks by quarter; there are three quarters.
int firstQuarter;
int secondQuarter;
int thirdQuarter;
String broker;
String Buy;
firstQuarter = 10;
secondQuarter = 30;
thirdQuarter = 20;
//Tell client the maximum value/price of the stock during the year.
System.out.println("The maximum price of a stock share in the year is: $" + secondQuarter + ".");
// Tell client the minimum value/price of the stock during the year.
System.out.println("The minimum price of a stock share in the year is: $" + firstQuarter + ".");
//Ask broker if you want to buy or sell
Scanner input = new Scanner(System.in);
System.out.println("Would you like to Buy or Sell stocks? Please use Buy or Sell commands.");
broker = input.next("");
if (broker == "Buy"){
//Calculate percentage increase of stock through year if the broker wants the client to buy.
//The values are relative to the start of the year.
double percentIncrease;
percentIncrease = (double)(endStock - beginningStock)/(beginningStock);
//Convert decimal to percentage and tell client percentage increase relative to beginning of year.
System.out.println("The percentage increase of the stock through the year, relative to beginning of year, is: %"+ ((int)(percentIncrease*100+.5))+ "." );
}
else if (broker == "Sell"){
//Calculate change relative to end of year
double endIncrease;
endIncrease = (double)(endStock - beginningStock)/(endStock);
//Convert decimal to percentage and tell client percentage increase relative to end of year.
System.out.println("The percentage increase of the stock through the year, relative to end of year, is: %"+ ((int)(endIncrease*100))+ "." );
}
}
}
The issue I am having is around line 29:
//Ask broker if you want to buy or sell
Scanner input = new Scanner(System.in);
System.out.println("Would you like to Buy or Sell stocks? Please use Buy or Sell commands.");
broker = input.next("");
if (broker == "Buy"){
//Calculate percentage increase of stock through year if the broker wants the client to buy.
//The values are relative to the start of the year.
double percentIncrease;
percentIncrease = (double)(endStock - beginningStock)/(beginningStock);
//Convert decimal to percentage and tell client percentage increase relative to beginning of year.
System.out.println("The percentage increase of the stock through the year, relative to beginning of year, is: %"+ ((int)(percentIncrease*100+.5))+ "." );
It will take the String but will not use it. I don't know what I am doing wrong. Forgive me this is my first post on here.
The problem is that == tests for reference-equality rather than value-equality; that is, it checks that the two sides are the same object, rather than equivalent objects. You need to change this:
if (broker == "Buy"){
to this:
if (broker.equals("Buy")){
Use equals() instead of == to compare strings.
== is the identity comparison operator, not equivalence.
As others said, you should use equals() to compare instances of String.
You have another problem in your code. You're using Scanner´s method next(String pattern), which will return a String if it matches the passed pattern. Since you're passing an empty Stringas the pattern it will raise an exception. You should be using next() instead.
"Buy".equals(broker) should be condition check
In Java string comparison should be .equals not ==

Categories