I'm writing this program that will let you enter in an amount for each quarters, dimes, nickels and pennies and return their amount in $. After that, I want to be able to add up the dollar amounts they produce without having to enter in all of the coin amounts a second time. Any ideas? Thanks in advance.
import java.util.*;
public class HalfDollar {
public static final Scanner CONSOLE = new Scanner(System.in);
public static void main(String[] args) {
quarterDollarAmount( );
dimeDollarAmount( );
nickelDollarAmount( );
pennyDollarAmount( );
totalDollarAmount( );
}
public static double quarterDollarAmount( ) {
System.out.print("Enter the number of quarters: ");
int quarterDollar = CONSOLE.nextInt( );
double amount = quarterDollar * 0.25;
System.out.println(quarterDollar + " Quarter are $" + amount);
return amount;
}
public static double dimeDollarAmount( ) {
System.out.print("Enter the number of dimes: ");
int dimeDollar = CONSOLE.nextInt( );
double amount = dimeDollar * 0.10;
System.out.println(dimeDollar + " Dimes are $" + amount);
return amount;
}
public static double nickelDollarAmount( ) {
System.out.print("Enter the number of nickels: ");
int nickelDollar = CONSOLE.nextInt( );
double amount = nickelDollar * 0.05;
System.out.println(nickelDollar + " Nickels are $" + amount);
return amount;
}
public static double pennyDollarAmount( ) {
System.out.print("Enter the number of pennies: ");
int pennyDollar = CONSOLE.nextInt( );
double amount = pennyDollar * 0.01;
System.out.println(pennyDollar + " Pennies are $" + amount);
return amount;
}
public static double totalDollarAmount( ) {
double quarter = quarterDollarAmount();
double dime = dimeDollarAmount();
double nickel = nickelDollarAmount();
double penny = pennyDollarAmount();
double total = quarter + dime + nickel + penny;
System.out.println("Total amount is $" + total);
return total;
}
}
Hmmm, this smells to me like a homework problem. If you are truly the one who wrote this code, any number of solutions should be pretty obvious. But whatever, I won't judge your journey. Since you are returning the amount from each method, just keep a running total of all the amounts as you go along, then change your totalDollarAmount method to take the total as input instead of asking for it again:
double total = 0.0;
total += quarterDollarAmount( );
total += dimeDollarAmount( );
total += nickelDollarAmount( );
total += pennyDollarAmount( );
totalDollarAmount( total );
You're not doing anything with your variables. Just calling them and then they're moving out of scope.
You could either store the returned value in a global variable to use later.
private double quarter, dime, total;
public static void main(String[] args) {
quarter = quarterDollarAmount();
dime = dimeDollarAmount();
total = (quarter + dime);
s.o.p(total);
}
If you don't care about the value after printing it out you can either total them up with local variables or literally just total up your methods as follows.
public static void main(String[] args) {
s.o.p(quarterDollarAmount( ) + dimeDollarAmount( ) + ....);
}
To get your value to 2 decimal places use something like the following:
DecimalFormat format = new DecimalFormat("#.00");
Double total_formatted = Double.parseDouble(format.format(total));
s.o.p(total_formatted);
That enforces the value to have 2 decimal places with an optional amount of digits left of the decimal place.
Final thing, you probably don't want to make everything static. It basically defeats the point of object orientation as static variable will persist throughout all objects of a class.
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'm trying to add together the sum of the iterations of a for loop. This is what I have so far.
import java.util.Scanner;
public class Pennies
{
public static void main (String [] args)
{
double amount; //To hold the amount of pennies per day
double days; //To hold the days user saved.
double total;
System.out.println("I will display a table of salary if you're paid every day in pennies and it doubles every day.");
Scanner keyboard = new Scanner(System.in);
System.out.print("How many days do you wish to save for?");
days = keyboard.nextDouble();
//Display the table
System.out.print("Day \t Salary \n");
for (amount = 1; amount <= days; amount++)
{
total = amount * .01 * amount;
System.out.println(amount + "\t \t $" + total);
}
}
}
Any help would be greatly appreciated!
In order to keep on adding the salary for each day and keeping the track of total for each day (as I get it from your statement), you can change:-
total = amount * .01 * amount;
to
total += amount * .01 * amount; // total = total + (amount*0.01*amount)
which(when not printing each day information separately) can be simplified as:-
total = amount * .01 * amount * days;
I compiled your code and noticed that your numbers were off. Assuming that you want the first day's pay to be one penny, and for it to double every following day, here's what I came up with. It's hard to tell if this is exactly what you want since you didn't actually ask a question, so let me know if this is what you're looking for.
public static void main(String[] args) {
System.out
.println("I will display a table of salary if you're paid every day in pennies and it doubles every day.");
Scanner keyboard = new Scanner(System.in);
System.out.print("How many days do you wish to save for?");
double days = keyboard.nextDouble();
// Display the table
System.out.print("Day \t Salary \n");
double pay = 0.01;
double totalPay = 0.0;
for (int i = 1; i <= days; i++) {
System.out.println(i + "\t \t $" + pay);
totalPay += pay;
pay *= 2;
}
System.out.println("Total Pay \t $" + totalPay);
keyboard.close();
}
You're originally doing total = amount*0.1*amount, which won't give you what you want. You're confusing squaring amount with simply doubling it.
Edit: Also consider changing days to an int. I don't see any reason why it should be a double
what the program wants me to code:
Code an executable program that will produce
an invoice for a customer ordering a number
of products at a store. A sample run of the
program is shown to the right.
Your program
must ask for the number of products (up to a
maximum of 12 products may be ordered) and
then successively ask for the product name and
its cost. The invoice produced includes:
the title of the store (as shown),
product names and their cost,
calculated cost of all products,
calculated 5% sales tax,
overall total cost
a thank you.
The products and their cost must be kept in
parallel arrays. Two methods must be coded.
One method will display the title. The second
method will accept the calculated cost of all
products and return the calculated sales tax.
The method that computes the sales tax must
use a named constant for the 5% tax rate.
picture of example run of what it should look like: http://imgur.com/F3XDjau
Currently my program is this so far, but im not sure if it is correct or if i need to make the variables into an array.
public static void main(String[] args) {
Scanner input= new Scanner(System.in);
int product;
String products;
double cost;
System.out.println("How many products? ");
product=input.nextInt();
for(int i = 0; i < product; i++){
System.out.println("Product Name: ");
products=input.next();
System.out.println("Cost: ");
cost=input.nextDouble();
}
}
}
this is how you can fill your array:
double[] costArray = new double[product];
for(int i = 0; i < product; i++){
costArray[i] = input.nextDouble();
}
You need to use an array for variables products and cost like this:
static final float TAXES = 0.05f;
public static void main(String[] args) {
double sum = 0.0;
double tax;
Scanner input = new Scanner(System.in);
int product;
String products[];
double cost[];
System.out.println("How many products? ");
product = input.nextInt();
products = new String[product];
cost = new double[product];
for (int i = 0; i < product; i++) {
System.out.println("Product Name: ");
products[i] = input.next();
System.out.println("Cost: ");
cost[i] = Double.parseDouble(input.next().trim().replace(',', '.'));
}
indentedText();
for (int i = 0; i < product; i++) {
System.out.printf(products[i] + '\t' + "%.2f %n", cost[i]);
sum = sum + cost[i];
}
tax = calculateTaxes(sum);
System.out.printf("Sub total:" + '\t' + "%.2f %n", sum);
System.out.printf("Sales tax:" + '\t' + "%.2f %n", tax);
System.out.printf("Total to be paid:" + '\t' + "%.2f %n %n", (sum + tax));
System.out.print('\t' + "Thank you!");
}
private static void indentedText() {
System.out.print('\t' + "The Company Store" + '\n' + '\n');
}
private static double calculateTaxes(double sum) {
return sum * TAXES;
}
I have the following code (I'm not very computer literate so be gentle) that the user is supposed to be able to enter individual coin amounts and the program will tell the user how much money they have in said coin amounts.
import java.util.*;
public class Coins {
public static final Scanner CONSOLE = new Scanner(System.in);
public static void main(String[] args) {
System.out.println ("Lab 2 by Maria T Williams\n");
quarterAmount( );
dimeAmount( );
nickelAmount( );
pennyAmount( );
}
public static void quarterAmount( ) {
System.out.print("Enter the number of quarters: ");
int quarterNumber = CONSOLE.nextInt( );
double amount = quarterNumber * 0.25;
System.out.print(quarterNumber + " You have $" + amount);
System.out.println(" worth of quarters.");
}
public static void dimeAmount( ) {
System.out.print("Enter the number of dimes: ");
int dimeNumber = CONSOLE.nextInt( );
double amount = dimeNumber * .10;
System.out.print(dimeNumber + " You have $" + amount);
System.out.println(" worth of dimes.");
}
public static void nickelAmount( ) {
System.out.print("Enter the number of nickels: ");
int nickelNumber = CONSOLE.nextInt( );
double amount = nickelNumber * 0.05;
System.out.print(nickelNumber + " You have $" + amount);
System.out.println(" worth of nickels.");
}
public static void pennyAmount( ) {
System.out.print("Enter the number of pennies: ");
int pennyNumber = CONSOLE.nextInt( );
double amount = pennyNumber * 0.01;
System.out.print(pennyNumber + " You have $" + amount);
System.out.println(" worth of pennies.");
}
}
If I enter an amount that has a number in the 100s place that isn't "0" I'm fine. But if I enter, say, two quarters I get back "$0.5" instead of "$0.50".
You could use a DecimalFormat to force the number to be formatted as you'd like it. E.g.:
DecimalFormat df = new DecimalFormat("#.00");
double amount = dimeNumber * .10;
System.out.print(dimeNumber + " You have $" + df.format(amount) + " worth of dimes.");
When outputting the result of your calculation, you can use a DecimalFormat like this:
DecimalFormat f = new DecimalFormat("#0.00");
System.out.println(f.format(dimeNumber));
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)