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.
Related
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
}
import java.util.*;
import java.math.*;
public class Arithmetic
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
double mealCost = scan.nextDouble(); // original meal price
double tipPercent = scan.nextDouble(); // tip percentage
double taxPercent = scan.nextDouble(); // tax percentage
scan.close();
// Write your calculation code here.
tipPercent = mealCost*tipPercent/100.0;
taxPercent =mealCost*taxPercent/100.0;
//cast the result of the rounding operation to an int and save it as totalCost
double totalCost = mealCost + tipPercent + taxPercent;
// Print your result
int total = (int)totalCost;
System.out.println("The total meal cost is " + total + " dollars.");
}
}
input:
20.75
10
3
expected output:The total meal cost is 23 dollars.
resulting output:The total meal cost is 26 dollars.
what's wrong with this program?
You do not use your tip and tax input.
It should be:
tipPercent = mealCost*tipPercent/100.0;
taxPercent = mealCost*taxPercent/100.0;
finally this code works perfectly
import java.util.*;
import java.math.*;
public class Arithmetic
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
double mealCost = scan.nextDouble(); // original meal price
double tipPercent = scan.nextDouble(); // tip percentage
double taxPercent = scan.nextDouble(); // tax percentage
scan.close();
// Write your calculation code here.
tipPercent = mealCost*tipPercent/100.0;
taxPercent =mealCost*taxPercent/100.0;
// cast the result of the rounding operation to an int and save it as
//totalCost
double totalCost = mealCost + tipPercent + taxPercent;
if((tipPercent + 0.5)>=((int)tipPercent + 1))
{
totalCost += 1;
}
else
{
}
// Print your result
int total = (int)totalCost;
System.out.println("The total meal cost is " + total + " dollars.");
}
}
I have to do this program where I have to display the calculation of the profit for each individual stock, but I also have to display the profit for the total amount of stocks. My code only has it so it displays the calculation for all of the stocks:
import java.util.Scanner;
public class KNW_MultipleStockSales
{
//This method will perform the calculations
public static double calculator(double numberShare, double purchasePrice,
double purchaseCommission, double salePrice,
double salesCommission)
{
double profit = (((numberShare * salePrice)-salesCommission) -
((numberShare * purchasePrice) + purchaseCommission));
return profit;
}
//This is where we ask the questions
public static void main(String[] args)
{
//Declare variables
Scanner scanner = new Scanner(System.in);
int stock;
double numberShare;
double purchasePrice;
double purchaseCommission;
double salePrice;
double saleCommission;
double profit;
double total = 0;
//Ask the questions
System.out.println("Enter the stocks you have: ");
stock = scanner.nextInt();
//For loop for the number stock they are in
for(int numberStocks=1; numberStocks<=stock; numberStocks++)
{
System.out.println("Enter the number of shares for stock " + numberStocks + ": ");
numberShare = scanner.nextDouble();
System.out.println("Enter the purchase price" + numberStocks + ": ");
purchasePrice = scanner.nextDouble();
System.out.println("Enter the purchase commissioned:" + numberStocks + ": ");
purchaseCommission = scanner.nextDouble();
System.out.println("Enter the sale price:" + numberStocks + ": ");
salePrice = scanner.nextDouble();
System.out.println("Enter the sales commissioned:" + numberStocks + ": ");
saleCommission = scanner.nextDouble();
profit = calculator(numberShare, purchasePrice, purchaseCommission,
salePrice, saleCommission);
total = total + profit;
}
//Return if the user made profit or loss
if(total<0)
{
System.out.printf("You made a loss of:$%.2f", total);
}
else if(total>0)
{
System.out.printf("You made a profit of:$%.2f", total);
}
else
{
System.out.println("You made no profit or loss.");
}
}
}
How can I get it so each individual stock profit gets shown, with the profit of all the stocks together?
Try maintaining a separate Map for profit/loss. You may want to accept Stock Name as an input which will help manage individual stocks effectively.
// Map of stock name and profit/loss
Map<String,Double> profitMap = new HashMap<String,Double>();
After calculating profit/loss, add entry to map
profitMap.put("stockName", profit);
total = total + profit;
At the end of your program, iterate and display profit/loss for each Stock from Map.
for (Entry<String, Integer> entry : profitMap.entrySet()) {
System.out.println("Stock Name : " + entry.getKey() + " Profit/loss" + entry.getValue());
}
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();
I am just about finished with a basic Cash Register program. Almost everything is working except the very end of the output where I have to show the daily total sales.
Cash Register class
public class CashRegister
{
private double purchase;
private double payment;
private double totalTax;
private double taxRate;
private double tax;
private double salesTotal;
private double salesCount;
private double amount;
private double rate;
private double taxPurchase;
private double taxable;
/**
Constructs a cash register with no money in it.
*/
public CashRegister(double rate)
{
purchase = 0;
payment = 0;
taxRate = rate;
}
/**
Records the sale of an item.
#param amount the price of the item
*/
public void recordPurchase(double amount)
{
purchase = purchase + amount;
salesTotal = amount + salesTotal;
}
/**
Records the sale of a taxable item and compute the total tax.
#param amount the price of the item
*/
public void recordTaxablePurchase(double amount)
{
//taxPurchase = taxPurchase + amount;
totalTax = totalTax + amount + (amount* (taxRate / 100));
}
/**
Enters the payment received from the customer.
#param amount the amount of the payment
*/
public void enterPayment(double amount)
{
payment = amount;
}
/**
Returns the total tax due
#return the totalTax
*/
public double getTotalTax()
{
return totalTax;
}
/**
Computes the change due and resets the machine for the next customer.
#return the change due to the customer
*/
public double giveChange()
{
double change = payment - purchase - totalTax;
salesTotal += purchase;
purchase = 0;
payment = 0;
//totalTax = 0;
salesCount++;
salesTotal++;
return change;
}
public double getSalesTotal(){
return purchase + totalTax;
}
public double getSalesCount(){
return salesCount;
}
public void reset(){
amount = 0;
purchase = 0;
totalTax = 0;
salesTotal = 0;
salesCount = 0;
}
public double showPayment(){
return payment;
}
public double getTotalPurchase(){
return payment + totalTax;
}
}
The Cash Register tester class
public class CashRegisterTester{
public static void main(String [] args){
CashRegister cash1 = new CashRegister(7.5);
System.out.println("Customer 1:");
cash1.recordPurchase(20.00);
cash1.enterPayment(20.00);
System.out.println(" Change is: " + cash1.giveChange());
System.out.println(" Expected is 0.0");
System.out.println();
System.out.println("Customer 2:");
cash1.recordPurchase(30.00);
cash1.recordPurchase(10.00);
cash1.enterPayment(50.00);
System.out.println(" Change is: " + cash1.giveChange());
System.out.println(" Expected is 10.0");
//cash1.reset();
System.out.println();
System.out.println("Customer 3:");
cash1.recordTaxablePurchase(80.00);
cash1.recordPurchase(70.00);
cash1.recordTaxablePurchase(50.00);
cash1.enterPayment(220.00);
System.out.println(" Total Sales: " + cash1.getSalesTotal());
System.out.println(" Payment Given: " + cash1.showPayment());
System.out.println(" Change is: " + cash1.giveChange());
System.out.println(" Expected is: 7.0");
System.out.println();
System.out.println(" Daily Totals: ");
System.out.println(" Total Sales: " + "$ " + cash1.getSalesTotal());
System.out.println(" Number of Sales: " + cash1.getSalesCount());
}
}
The current output is :
Customer 1:
Change is: 0.0
Expected is 0.0
Customer 2:
Change is: 10.0
Expected is 10.0
Customer 3:
Total Sales: 209.75
Payment Given: 220.0
Change is: 10.25
Expected is: 7.0
Daily Totals:
Total Sales: $ 139.75
Number of Sales: 3.0
Everything is correct except for the total sales under Daily Totals, which should be 269.75. I am confused as to why this will not work. Any help would be great, thank you.
Each time you call giveChange() you're resetting your purchase amounts back to 0. Your giveSalesCount therefore is only returning the total purchases that are totalled from your taxable sales.
Either store the payment amount elsewhere when you're calculating the change or find another way to make that calculation without removing your purchases.