import java.util.Scanner;
import javax.swing.JOptionPane;
public class RestaurantBill3
{
public static void main(String [] args)
{
//Constant
final double TAX_RATE = 0.0675;
final double TIP_PERCENT = 0.15;
//Variables
double cost;
double taxAmount = TAX_RATE * cost; //Tax amount
double totalWTax = taxAmount + cost; //Total with tax
double tipAmount = TIP_PERCENT * totalWTax; //Tip amount
double totalCost = taxAmount + tipAmount + totalWTax; //Total cost of meal
Scanner keyboard = new Scanner(System.in);
System.out.print("What is the cost of your meal? ");
cost = keyboard.nextDouble();
System.out.println("Your meal cost $" +cost);
System.out.println("Your Tax is $" + taxAmount);
System.out.println("Your Tip is $" + tipAmount);
System.out.println("The total cost of your meal is $" + totalCost);
System.exit(0); //End program
}
}
/*
I keep receiving the error that cost has evidently not been initialized, but if it's waiting on input, how is it supposed to do that?*/
You are referring to the value of cost before it's initialized here:
double taxAmount = TAX_RATE * cost;
double totalWTax = taxAmount + cost;
Move the initialization of those variables after the initialization of cost, so cost will have a value when it's referenced.
Look at how you declare the variable cost. You are declaring a variable but you are not assigning it a value, hence it being uninitialized. I think there is a bigger conceptual problem though. Let's look at your code:
double cost; // this is uninitialized because it has not been assigned a value yet
double taxAmount = TAX_RATE * cost; //Tax amount
double totalWTax = taxAmount + cost; //Total with tax
double tipAmount = TIP_PERCENT * totalWTax; //Tip amount
double totalCost = taxAmount + tipAmount + totalWTax; //Total cost of meal
Here, what is happening is you are declaring variables and setting their value to be the result of the expression - the right hand side of the equals sign. The program flow is top down, in this case, and these statements are executed sequentially. When taxAmount and your other variables are declared and assigned, the value of cost is unknown. This results in a compiler error. Try rewriting your code like this, keeping in mind that cost needs be assigned a value before using it.
public static void main(String [] args) {
//Constant
final double TAX_RATE = 0.0675;
final double TIP_PERCENT = 0.15;
//Variables
double cost, taxAmount; // rest of variables
Scanner keyboard = new Scanner(System.in);
System.out.print("What is the cost of your meal? ");
cost = keyboard.nextDouble();
System.out.println("Your meal cost $" +cost);
taxAmount = TAX_RATE * cost;
System.out.println("Your Tax is $" + taxAmount);
// rest of code
System.exit(0);
}
Related
I feel like I am missing some form of conversion. I am still new to Java so I don't know much about it. Please help.
public static void main(String[] args){
String mealCharge;
double tax;
double tip;
double total;
tax = mealCharge * 0.0625; //food tax is 6.25%
tip = mealCharge * 0.15; //tip is 15%
total = mealCharge + tax + tip;
mealCharge = JOptionPane.showInputDialog("Please enter the charge for the meal.");
JOptionPane.showMessageDialog(null, "Your total will be $" + total ".");
}
}
In your code mealCharge is a String data type. But you can't use String type in the calculations. You need to convert mealCharge to the double/int/float/large/short data type. I assume, you need it to be a double type.
So, what I did I create a new variable for user input String mealChargeInput and new variable double mealCharge;. And then I convertend string to double by using Integer.parseInt() method.
Here's the code:
public static void main(String[] args) {
String mealChargeInput; //Create a different name for "mealCharge" string
double mealCharge;
double tax;
double tip;
double total;
mealChargeInput = JOptionPane.showInputDialog("Please enter the charge for the meal.");
System.out.println(mealChargeInput.getClass().getSimpleName());
mealCharge = Double.parseDouble(mealChargeInput); // Convert string value of "mealChargeInput" to the double value and assign it to a new double variable
tax = mealCharge * 0.0625; //food tax is 6.25%
tip = mealCharge * 0.15; //tip is 15%
total = mealCharge + tax + tip;
JOptionPane.showMessageDialog(null, "Your total will be $" + total +"."); //Missing "+" operator;
}
Is it what you need?
You cant multiply a string (ie, mealCharge) with Double(ie, tip/tax). Change your datatype of the mealCharge to Double and you are good to go.
From your code, I believe you will need to convert variable into the same type.
As string mealcharge can not be * with a double - other data types.
You would have to convert it into the same type depending on what you would want - in this case would be double.
This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 1 year ago.
Here is my current program where it asks the user to input the item they're buying and the original price. The program will take a random percent off (between 5-75) and then give the user the new total price including a .07 tax added. The code is working great just that I'm not sure how to get the price amount to round to $0.00 and not have trailing numbers which ends up affecting the coins/dollars that the cash register would give in change. Any ideas? Thanks!
import java.util.Scanner;
import java.lang.Math;
import java.math.*;
import java.util.Random;
//declaring variables for methods
class Main
{
Scanner scan = new Scanner(System.in);
//random variable for while loop
int k=1;
//other variables
String name;
double taxRate = 0.07;
int dollars, quarters, dimes, nickels, cent, discountPercentage;
double discount, salePrice, tax, totalPrice, money, change, originalPrice, cents;
//method to run entire program
public void runProgram()
{
//make sure to create program including a while loop
while (k<2)
{
//here it explains the calculations and gets the user input of the item and original price of it
System.out.println("As part of a store promotion, each customer is given a random percent off");
System.out.println("Please enter the name of the item you plan to purchase: ");
name = scan.nextLine();
System.out.println("Enter the original price of that item: ");
originalPrice = scan.nextDouble();
scan.nextLine();
//here is where the user input is being calculated
discountPercentage = getDiscount();
discount = calculateDiscount(originalPrice, discountPercentage);
salePrice = calculateSalePrice(originalPrice, discount);
tax = calculateTax(salePrice);
totalPrice = calculateTotalPrice(salePrice, tax);
//print to user all the new calculations of item price
System.out.println("The original price of the item is: " + originalPrice);
System.out.println("The discount percent on the item is: " + discountPercentage + "%");
System.out.println("The new sale price of the item is: " + salePrice);
System.out.println("The tax of the item is: " + tax);
System.out.println("Now, the new total price of the item including the discount and tax is: " + totalPrice);
//this part will figure out how much money the user is giving the cashier and how much change needs to be given
System.out.println("How much money are you giving to the cashier?");
money = scan.nextDouble();
scan.nextLine();
change = solveChange(money, totalPrice);
System.out.println("The change you will be given back is: " + change);
convertChange(change);
System.out.println("\n");
}
}
//method for getting random discount for the item
public int getDiscount()
{
//discount can only be in multiples in 5 ranging from 5-75, and all the variables for this method
int multiple = 5;
int discountStart = 5;
int discountEnd = 75;
int calculateDiscountStart;
int calculateDiscountEnd;
calculateDiscountStart = discountStart / multiple;
calculateDiscountEnd = discountEnd / multiple;
//random generator for the discount
discountPercentage = new Random().nextInt(1 + calculateDiscountEnd - calculateDiscountStart) + calculateDiscountStart;
return discountPercentage * multiple;
}
//method for calculating the discount percent that is applied to original price of item
public double calculateDiscount(double originalPrice, int discountPercentage)
{
discount = originalPrice * discountPercentage / 100;
return discount;
}
//method to calculate the price with the discount applied to the item
public double calculateSalePrice(double originalPrice, double discount)
{
salePrice = originalPrice - discount;
return salePrice;
}
//method to calculate the tax
public double calculateTax(double salePrice)
{
tax = salePrice * taxRate;
return tax;
}
//method that will calculate the overall price including tax (adding previous methods together)
public double calculateTotalPrice(double salePrice, double tax)
{
totalPrice = salePrice + tax;
return totalPrice;
}
//method that takes user input of how much money giving and calculating how much change they need
public double solveChange(double money, double totalPrice)
{
change = money - totalPrice;
//int dollars = change/1;
return change;
}
//method to convert the change the user needs to dollars, quarters, etc
public double convertChange(double change)
{
cents = change*100;
dollars = (int)cents/100;
quarters = (int)(cents % 100)/25;
dimes = (int)((cents%100)%25)/10;
nickels = (int)(((cents%100)%25)%10)/5;
cent = (int)((((cents%100)%25)%10)%5);
//printing out the amount of change to the user
System.out.println("Amount of change in Dollars is: " + dollars);
System.out.println("Amount of change in Quarters is: " + quarters);
System.out.println("Amount of change in Nickels is: " + nickels);
System.out.println("Amount of change in Dimes is: " + dimes);
System.out.println("Amount of change in Cents is: " + cent);
return change;
}
//main method using static
public static void main(String[] args) {
Main prog = new Main();
prog.runProgram();
}
}
What you usually do in real world programs that involve money: you use an int that is the total amount of pennies. So $ 1.99 = 199 int.
I have to write a program application that allows an employee to enter the number of burgers, fries, and soft drinks that a customer orders.
After my "final total", I should have another part that says "Enter Amount tendered:" and "Change:" from the customer. I have the code written out, I'm not sure what to write out for the amount tendered and the change?
public class FastFood {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
final double pburgers=2.49;
final double pfries=1.89;
final double psodas=0.99;
final double ptax=0.13;
double burgers;
double fries;
double sodas;
double totaltax;
double total;
double tax;
Scanner input = new Scanner(System.in);
System.out.print("Enter the amount of burgers: ");
burgers = input.nextDouble();
System.out.print("Enter the amount of fries: ");
fries = input.nextDouble();
System.out.print("Enter the amount of soft drinks: ");
sodas = input.nextDouble();
totaltax = (burgers*pburgers)+(fries*pfries)+(sodas*psodas);
tax = totaltax*ptax;
total = totaltax + tax;
System.out.format("Total before tax is: $%-5.2f\n", totaltax);
System.out.format("Tax: $%-5.2f\n", tax);
System.out.format("Your final total is: $%-5.2f\n", total);
}
}
import java.util.Scanner;
public class FastFood {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
final double pburgers=2.49;
final double pfries=1.89;
final double psodas=0.99;
final double ptax=0.13;
double burgers;
double fries;
double sodas;
double totaltax;
double total;
double tax;
double tender;
double change;
Scanner input = new Scanner(System.in);
System.out.print("Enter the amount of burgers: ");
burgers = input.nextDouble();
System.out.print("Enter the amount of fries: ");
fries = input.nextDouble();
System.out.print("Enter the amount of soft drinks: ");
sodas = input.nextDouble();
totaltax = (burgers*pburgers)+(fries*pfries)+(sodas*psodas);
tax = totaltax*ptax;
total = totaltax + tax;
System.out.format("Total before tax is: $%-5.2f\n", totaltax);
System.out.format("Tax: $%-5.2f\n", tax);
System.out.format("Your final total is: $%-5.2f\n", total);
System.out.print("Enter amount tendered: " );
tender = input.nextDouble();
change = tender - total;
System.out.format("Change: $%-5.2f\n", change);
}
}
I need to use two methods. One is getMealCharge() and needs to return a mealCharge and no argument. The second is computeAndPrintTotalBill() and needs to do calculation in that method.
My question is- when I get the user input from first method, how do I get that number to apply to the second method so it can calculate.
If I put everything on the first method, it will work. But, for some reasons in the second method it won't show up. If anyone can please help me finding what I am doing wrong. Thank you.
import java.util.Scanner;
public class ComputeTip{
final double taxRate = 0.0725;
final double tipRate = 0.15;
double mealCharge;
double tax;
double tip;
double total;
public double getMealCharge(){
System.out.println("Enter meal charge: ");
Scanner keyboard = new Scanner(System.in);
mealCharge = keyboard.nextDouble();
return mealCharge;
}
public void computeAndPrintTotalBill(double getMealCharge, double mealCharge){
Scanner keyboard = new Scanner(System.in);
tax = mealCharge * taxRate;
tip = mealCharge * tipRate;
total = mealCharge + tax + tip;
Test.println("charge: " + mealCharge);
Test.println("tax: " + tax);
Test.println("tip: " + tip);
Test.println("total: " + total);
}
}
You are using the parameters wrong.
Try this:
public void computeAndPrintTotalBill(){
double mealCharge = getMealCharge();
tax = mealCharge * taxRate;
tip = mealCharge * tipRate;
total = mealCharge + tax + tip;
Test.println("charge: " + mealCharge);
Test.println("tax: " + tax);
Test.println("tip: " + tip);
Test.println("total: " + total);
}
You can use only computeAndPrintTotalBill method to get your work done by modifying your methods and variable as below:
final static double taxRate = 0.0725;
final static double tipRate = 0.15;
public static void computeAndPrintTotalBill(double mealCharge) {
double tax= mealCharge * taxRate;
double tip = mealCharge * tipRate;
double total= mealCharge + tax + tip;
System.out.println("charge: " + mealCharge);
System.out.println("tax: " + tax);
System.out.println("tip: " + tip);
System.out.println("total: " + total);
}
public static void main(String...args){
Scanner keyboard = new Scanner(System.in);
Double mealCharge = keyboard.nextDouble();
computeAndPrintTotalBill(mealCharge);
}
OUTPUT:
21.5
charge: 21.5
tax: 1.5587499999999999
tip: 3.225
total: 26.28375
Note: You can also do
ComputeTip computeTip = new ComputeTip();
double mealCharge = computeTip.getMealCharge();
computeTip.computeAndPrintTotalBill(mealCharge);
In your original program (Need to remove double getMealCharge from your method signature). This also works fine.
I have to create a virtual coffee shop where the user enters their order number, how many of that order they want, calculate the subtotal and the discount, etc. The whole point of this is that the process's divided into various methods. Most of the methods are pretty simple, but I'm having trouble with the computeSubTotal method. I have to initialize subtotal in the main method to make this work, but when the subtotal's calculated in computeSubTotal, it always ends up being zero. Sorry if this seems stupid, but I have no idea what I'm doing wrong, help?
import java.util.Scanner;
public class CoffeeShopWithMethods
{
public static void main(String[] args)
{
Scanner user_input = new Scanner (System.in);
String user_name;
System.out.print("\nPlease enter your name: ");
user_name = user_input.next();
System.out.println("\nWelcome to the Java Byte Code Coffee Shop, " + user_name + "!");
int orderNumber = 0;
int orderQuan = 0;
double subTotal = 0.0;
//Beginning of calls to methods
displayMenu();
getItemNumber(orderNumber);
getQuantity(orderQuan);
computeSubTotal(orderNumber, orderQuan, subTotal);
discountCheck(subTotal);
}
public static void displayMenu()
{
System.out.println("\nHere is our menu: \n" + "\n 1. Coffee $1.50" + "\n 2. Latte $3.50" + "\n 3. Cappuccino $3.25" + "\n 4. Espresso $2.00");
}
public static int getItemNumber(int orderNumber) //prompts user for item number (1 for coffee, 2 for latte, etc...)
{
Scanner user_input = new Scanner(System.in);
System.out.print("\nPlease enter the item number: ");
orderNumber = user_input.nextInt();
final double Coffee = 1.50;
final double Latte = 3.50;
final double Cappuccino = 3.25;
final double Espresso = 2.00;
double Cost = 0;
if (orderNumber == 1)
Cost = Coffee;
if (orderNumber == 2)
Cost = Latte;
if (orderNumber == 3)
Cost = Cappuccino;
if (orderNumber == 4)
Cost = Espresso;
return orderNumber;
}
public static int getQuantity(int orderQuan)
{
Scanner user_input = new Scanner(System.in);
System.out.print("\nPlease enter the quantity: ");
orderQuan = user_input.nextInt();
return orderQuan;
}
public static double computeSubTotal(int orderNumber, int orderQuan, double subTotal)
{
subTotal = (orderNumber * orderQuan);
System.out.print("Your total before discount and tax is: $" + subTotal);
return subTotal;
}
public static boolean discountCheck(double subTotal) //takes subtotal and returns true if user earned a discount (over $10)
{
if (subTotal >= 10.00)
return true;
else
return false;
}
}
Your methods getItemNumber, getQuantity, computeSubTotal and discountCheck all return a value, but you are not storing that return value in your main method.
In addition to that, your getItemNumber() method is only storing the cost locally, which is then discarded when the method is finished - the cost should be returned (and the method probably renamed).
You probably should have something like this:
//Beginning of calls to methods
displayMenu();
double itemCost = getItemCost(); // was getItemNumber()
orderQuan = getQuantity(orderQuan);
subTotal = computeSubTotal(itemCost, orderQuan);
boolean shouldDiscount = discountCheck(subTotal);
Of course, to use an object-oriented approach, the variables should be members of your class, then you wouldn't need to pass or return values - they would be accessible to all methods in the class.
public static double computeSubTotal(int orderNumber, int orderQuan, double subTotal)
{
subTotal = (orderNumber * orderQuan);
System.out.print("Your total before discount and tax is: $" + subTotal);
return subTotal;
}
In your computeSubTotal method, you do
subTotal = (orderNumber * orderQuan);
This is not going to intiailize the variable in the main method; you are re-initializing the parameter variable.
In your main method, you should be doing
subTotal = computeSubTotal(orderNum, orderQuan);
instead of calling the method without using the return value. You might have noticed that I didn't pass subTotal to the method. This is not needed. You can instead re-declare the variable inside the method:
public static double computeSubTotal(int orderNumber, int orderQuan)
{
double subTotal = (orderNumber * orderQuan);
System.out.print("Your total before discount and tax is: $" + subTotal);
return subTotal;
}
This applies to the other variables aswell. Java is pass-by-value, so if you pass a value to a method, a new reference is created for the method (when you do int varName in your method's parameters when you declare the method)