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.
Related
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 this assignment and I am about to throw this laptop. The following code runs, but when I test it in MindTap I get the bottom message. I don't know what I am doing wrong or why it says incorrect.
Assignment:
Write three overloaded computeBill methods for a photo book store:
When computeBill receives a single parameter, it represents the price of one photo book ordered. Add 8% tax, and return the total due.
When computeBill receives two parameters, they represent the price of a photo book and the quantity ordered. Multiply the two values, add 8% tax, and return the total due.
When computeBill receives three parameters, they represent the price of a photo book, the quantity ordered, and a coupon value. Multiply the quantity and price, reduce the result by the coupon value, and then add 8% tax and return the total due.
My Coding:enter code here
public class Billing {
public static void main(String args[]){
double yourTotal;
yourTotal = computeBill(31.00);
displayTotal (yourTotal);
yourTotal = computeBill (31, 2);
displayTotal(yourTotal);
yourTotal = computeBill(31, 2, .2);
displayTotal (yourTotal);
}
public static double computeBill (double price)
{double total = price * 1.08;
System.out.println ("You ordered 1 photobook for $" + price);
System.out.println("Plus sales tax 8%");
return total;}
public static double computeBill (double price, int qty) {
double subtotal = price * qty;
double total = subtotal * 1.08;
System.out.println ("You ordered" + qty + " photobook(s) for $" + price);
System.out.println("Subtotal =" + subtotal);
System.out.println("Plus sales tax 8%");
return total;
}
public static double computeBill (double price, int qty, double discount) {
double subtotal = price * qty;
subtotal = subtotal - (subtotal * discount);
double total = subtotal * 1.08;
System.out.println ("You ordered " + qty + " photobook(s) for $" + price);
System.out.println("Subtotal = " + subtotal);
System.out.println("Less your " + (discount * 100) + "% discount");
System.out.println("Plus sales tax 8%");
return total;
}
public static void displayTotal (double total){
System.out.println("Total: $" + total);
}
}
Result MindTap gives me when I test:
Build Status
Build Succeeded
Test Output
You ordered2 photobook(s) for $31.0
Subtotal =62.0
Plus sales tax 8%
[FAILED]: unitTest(CodevolveTest12f618f0): null
false
Test Contents
Billing tester30 = new Billing();
#Test
public void unitTest() {
assertTrue(tester30.computeBill(31, 2) == 66.96);
}
Someone please help me. I am sooooo stuck!!!`
You need to limit the digits after decimal so that comparison becomes logical as:
public static double computeBill (double price, int qty) {
double subtotal = price * qty;
double total = subtotal * 1.08;
System.out.println ("You ordered" + qty + " photobook(s) for $" + price);
System.out.println("Subtotal =" + subtotal);
System.out.println("Plus sales tax 8%");
// need to limit to two digit after decimal
return Double.parseDouble(new DecimalFormat("##.##").format(total));
}
So, you test:
#Test
public void unitTest() {
assertTrue(tester30.computeBill(31, 2) == 66.96); // comparing two digits after decimal
}
Started taking a Java class at school and doing extra credit
and need help figuring out how to just have 2 decimal places.
Thank you for the help.
Christopher
import java.util.Scanner;
public class ChapterTwoEx8 {
public static void main(String[] args) {
//Create a Scanner object to read keyboard input.
Scanner keyboard = new Scanner(System.in);
//Declare Constants
final double SALES_TAX_RATE = 0.07;
final double TIP = 0.15;
//Declare Variables
double yourMealsPrice;
double wifeMealsPrice;
double sum;
double tip;
double totalCostOfMeal;
double salesTax;
//Get the prices of the meals.
System.out.println("Please enter the price of your wives meal.");
wifeMealsPrice = keyboard.nextDouble();
System.out.println("Please enter the price of your meal.");
yourMealsPrice = keyboard.nextDouble();
//Calculate cost of the meals.
sum = (double) wifeMealsPrice + yourMealsPrice;
//Calcute the sales tax
salesTax = (double) sum * SALES_TAX_RATE;
//Calcute tip
tip = (double) sum * TIP;
//Calcute total cost of meal
totalCostOfMeal = (double) sum + tip + salesTax;
System.out.println("Your meals were $ " + sum);
System.out.println("The total tax you paid is $ " + salesTax);
System.out.println("The tip you should leave is $ " + tip);
System.out.println("The amount of money you paid to keep your wife happy this night is $ " + totalCostOfMeal);
}
}
Use NumberFormat
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(2);
String formattedSum = nf.format(sum);
System.out.println("Your meals were $ " + formattedSum);
System.out.println("The total tax you paid is $ " + nf.format(salesTax));
System.out.println("The tip you should leave is $ " + nf.format(tip));
System.out.println("The amount of money you paid to keep your wife happy this night is $ " + nf.format(totalCostOfMeal));
Or, you could get rid of the dollar signs and just use NumberFormat.getCurrencyInstance();
instead of using NumberFormat.getInstance();
public class Purchase
{
int invoiceNumber = 1234;
double salePrice = 10.00;
double SalesTax;
public void setInvoiceNumber(int invoice)
{
invoiceNumber = invoice;
}
public void setSalePrice(double saleAmount)
{
salePrice = saleAmount;
SalesTax = (saleAmount * .05);//when I'm compiling it's not calculating
}
public void displaySalePrice()
{
System.out.println("Your invoice number is:" + invoiceNumber + ".");
System.out.println("Your sale amount is: " + salePrice + ".");
System.out.println("Your sales tax is: " + SalesTax + ".");
}
}
Your invoice number is:1234.
Your sale amount is: 10.0.
Your sales tax is: 0.0.-------Problem area
----jGRASP wedge2: exit code for process is 0.
----jGRASP: operation complete.
This will work...
public class Purchase
{
int invoiceNumber = 1234;
double salePrice = 10.00;
double SalesTax = 0.0; // by default this is initialized to zero.
public void setInvoiceNumber(int invoice)
{
invoiceNumber = invoice;
}
public void setSalePrice(double saleAmount)
{
salePrice = saleAmount;
SalesTax = (saleAmount * .05);//when I'm compiling it's not calculating
}
public void displaySalePrice()
{
System.out.println("Your invoice number is:" + invoiceNumber + ".");
System.out.println("Your sale amount is: " + salePrice + ".");
System.out.println("Your sales tax is: " + SalesTax + ".");
}
public static void main(String args[])
{
setSalePrice(10.0); // sets SalesTax to (100.0 * .05)
displaySalePrice();
}
}
Note that there are some stylistic issues with this class.
"SalesTax" starts with an upper case letter, which is supposed to be reserved for class (and interface) names. The correct spelling is "salesTax".
It lacks a constructor.
Example Constructor:
public Purchase(int invoiceN, double salesP, doubles salesT) {
invoiceNum = invoiceN;
salesPrice = salesP;
salesTax = salesT;
}
A purchase is a thing that doesn't change once it is made. Its data members are variable (change-able), but they should be invariable (final or constant).
final int invoiceNumber; // These are set in the Constructor.
final double salePrice; // Once they are set, they don't change.
final double salesTax;
The class has setters (which set/change the variables), but it lacks getters (which retrieve the values of the variables without changing them). In general, variables should be declared "private" and "final" whenever possible. So if I wrote this class, I would have written it like this:
Revised example:
public class Purchase
{
private final int invoiceNumber;
private final double salePrice;
private final double salesTax;
// Constructor
public Purchase(int invoiceN, double salesP) {
invoiceNum = invoiceN;
salesPrice = salesP;
salesTax = salesPrice * .05; // The Constructor can figure this out.
}
public int getInvoiceNumber()
{
return this.invoiceNumber; // "this." is optional
}
public double getSalePrice()
{
return this.salePrice();
}
public double getSalesTax()
{
return this.salesTax;
}
public void displaySalePrice()
{
System.out.println("Your invoice number is:" + getInvoiceNumber() + ".");
System.out.println("Your sale amount is: " + getSalePrice() + ".");
System.out.println("Your sales tax is: " + getSalesTax() + ".");
}
public static void main(String args[])
{
Purchase shoesPurchase = new Purchase(1234, 10.00);
shoesPurchase.displaySalePrice();
}
}
You are never using the setSalePrice method, hence your SalesTax parameter is never being initialized. You could initialize it like so: double SalesTax = salePrice * 0.05;
You are never calling setSalePrice, so the sales tax never gets set
here's one way to correct this, though really you should probably call setSalePrice before calling displaySalePrice, rather than inside of it
public void displaySalePrice()
{
setSalePrice(salePrice);
System.out.println("Your invoice number is:" + invoiceNumber + ".");
System.out.println("Your sale amount is: " + salePrice + ".");
System.out.println("Your sales tax is: " + SalesTax + ".");
}
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);
}