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.");
}
}
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 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());
}
/**I am trying to ask for user input for the number of the books they want to order, then using for find the cost of each book, total them up and give them their receipt at the end for their order. I understand how to give them the output just having trouble with my loop.*/
import java.util.Scanner;
public class BookOrder {
public static void main(String[] orgs){
Scanner in = new Scanner(System.in);
final double TAX = .065;
final double SHIPPING = 2.95;
int counter = 0;
double bookSubtotal, subtotal, taxPaid;
System.out.print("Please enter the number of books you're ordering: ");
double numberOfBooks = in.nextDouble();
for (counter = 0; counter < numberOfBooks; counter++){
System.out.println("Please enter the cost of your book: ");
double priceOfBooks = in.nextDouble();
bookSubtotal = priceOfBooks + bookSubtotal;
counter ++;
}
double subtotal = numberOfBooks * priceOfBooks;
double taxpaid = subtotal * (TAX);
double shippingCharge = SHIPPING * numberOfBooks;
double sumOfOrder = bookSubtotal + priceOfOrder + shippingCharge + TAX;
System.out.println("Number of books purchased:" + numberOfBooks);
System.out.println("Book subtotal: $" + subtotal);
System.out.println("Tax: $" + taxPaid);
System.out.println("Shipping: $" + shippingCharge);
System.out.println("-------------------------------");
System.out.println("The price of the order is $" + sumOfOrder + ".");
}
}
You seem to increment counter twice:
for (counter = 0; counter < numberOfBooks; counter++){
System.out.println("Please enter the cost of your book: ");
double priceOfBooks = in.nextDouble();
bookSubtotal = priceOfBooks + bookSubtotal;
counter ++;//this line
}
What happens in this line is that you increment counter, but the loop does that for you, because of:
for(counter = 0;counter<numberOfBooks;counter++)
the counter++ in that line increments counter for you, so just remove the
counter++;
line in the for loop (the one I wrote this line next to)
Also, you should set a value to bookSubtotal:
int bookSubtotal = 0;
in the beginning.
Additionally, you might want to make numberOfBooks an integer:
int numberOfBooks = in.nextInt();
And you shouldn't re declare subtotal twice, just remove the word double in the line:
double subtotal = (double)numberOfBooks * priceOfBooks;
Nor do you need the create taxpaid before the loop, because you have taxPaid after it. Naming is case sensitive, meaning capital letters Are ImpOrtaNt...
public class BookOrder {
public static void main(String[] orgs){
Scanner in = new Scanner(System.in);
final double TAX = .065;
final double SHIPPING = 2.95;
int counter = 0;
double bookSubtotal = 0;
System.out.print("Please enter the number of books you're ordering: ");
int numberOfBooks = in.nextInt();
for (counter = 0; counter < numberOfBooks; counter++){
System.out.println("Please enter the cost of your book: ");
double priceOfBooks = in.nextDouble();
bookSubtotal += priceOfBooks;
}
double shippingCharge = SHIPPING * numberOfBooks;
double tax = TAX * bookSubtotal;
double sumOfOrder = bookSubtotal + shippingCharge + tax;
System.out.println("Number of books purchased:" + numberOfBooks);
System.out.println("Book subtotal: $" + bookSubtotal);
System.out.println("Tax: $" + tax);
System.out.println("Shipping: $" + shippingCharge);
System.out.println("-------------------------------");
System.out.println("The price of the order is $" + sumOfOrder + ".");
}
}
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 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.