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
Related
I need an instance in my program to work in that if the user inputs a payment number (payment) that is equal to the total price of a checkout with taxation (price3), the program will just list 0.00 as change and not repeat user input as if the user's payment is less than the price. However, when payment equals price3 (payment - price3 == 0), the program goes to the else-if statement. How do I fix this?
Example: price3 == 28, payment == 28, the output after payment input is "You still owe..." and so on instead of "Your change is $0.00".
I think it is skipping the first if-statement in the while loop, but I have no idea why. I already tried moving around the if-statements in the while-loop to no avail.
There are no error messages.
Note: I am still trying to learn Java. Just started recently.
The program code which my question references is displayed below:
import java.util.Scanner;
public class Checkout
{
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
System.out.println("How many items are you purchasing?");
int count = input.nextInt();
double price1 = 0;
double price2 = 0;
String userItem = "";
for(int i = 1; i<=count; i++)
{
System.out.println("Please enter the name of the item:");
input.nextLine();
userItem = input.nextLine();
System.out.println("Please enter the price of the item:");
price1 = input.nextDouble();
System.out.println();
System.out.printf("Your item #" + i + " is " + userItem + " with a price of $" + "%.2f", price1);
System.out.println();
price2 = price2 + price1;
}
System.out.println();
System.out.printf("Your total amount is: $" + "%.2f", price2);
double price3 = price2 + (price2 * 0.06);
System.out.println();
System.out.printf("Your total amount with tax is: $" + "%.2f", price3);
System.out.println();
System.out.println("I need a payment!");
double payment = input.nextDouble();
boolean condition = false;
while(condition == false)
{
if(payment - price3 == 0)
{
condition = true;
}
else if(payment < price3)
{
System.out.println();
System.out.printf("You still owe " + "%.2f", (price3-payment));
System.out.println();
System.out.println("I need a better payment!");
payment = input.nextDouble();
}
else
{
condition = true;
}
}
double change = payment - price3;
System.out.println();
System.out.printf("Your change is: $" + "%.2f", change);
}
}
The core of your problem lies in (1) expecting exact equality of floating-point value, and (2) displaying quantities to 2 decimal places.
Given the user is told the amount to pay (price3) using 2 places of decimals, even if he enters that exact same value as payment, it may not match the true value of price3.
Ideally you should do all calculation in pennies (or whatever the smaller unit of this currency is). Failing that, your criterion for having paid the right amount should be something like the difference between price and payment is less than 0.01.
In the stated case
Example: price3 == 28, payment == 28, the output after payment input
is "You still owe..." and so on instead of "Your change is $0.00".
if the price before tax is 26.415 it makes the price after tax 27.9999, which displays as 28.00 but is not equal to 28.00. Neither 26.41 nor 26.42 get you to an after-tax displayed price of 28.00.
that is happening because of price3=price2+(price2*0.06). So, when it is comparing payment with price3, it is always less. See below
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.
Hello guys, this is my first time i post something in here and i just started learning java. This is my assignment and i need to write a payroll code with array. However, i dont understand why i cant get it to work. Somehow, it only calculate the last employee, the first and second are not included. If you guys can help i'd appreciate it. Thank you!
public class ArrayIG
{
public static void main(String[] args)
{
final int NUM_EMPLOYEES = 3;
//creating array
int[]hours = new int[NUM_EMPLOYEES];
int[] employeeID = {5678459, 4520125, 7895122};
double payRate;
double wages = 0;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter your " + NUM_EMPLOYEES + " employees work hours and pay rate:");
//get the hours
for (int i = 0; i < NUM_EMPLOYEES; i++)
{
System.out.print("Employee #" + employeeID[i] + ": ");
hours[i] = keyboard.nextInt();
//get the hourly pay rate
System.out.print("Enter the pay rate: ");
payRate = keyboard.nextDouble();
wages = hours[i] * payRate;
}
//display wages
System.out.println("The hours and pay rates you entered are:");
for(int i = 0; i < NUM_EMPLOYEES; i++)
{
System.out.printf("The total wages for Employee #%d is $%.2f\n", employeeID[i], wages);
}
}
}
MY OUTPUT:
Enter your 3 employees work hours and pay rate:
Employee #5678459: 35
Enter the pay rate: 21
Employee #4520125: 37
Enter the pay rate: 18.5
Employee #7895122: 39
Enter the pay rate: 37.25
The hours and pay rates you entered are:
The total wages for Employee #5678459 is $1452.75
The total wages for Employee #4520125 is $1452.75
The total wages for Employee #7895122 is $1452.75
Either create an array of wages or calculate wages in loop where wages are being print. And you should do assignments on your own đŸ˜€
You're collecting 3 different hours but only storing them in one value. The same for the wages. What happens when you store them as an array?
import java.util.Scanner;
public class ArrayIG
{
public static void main(String[] args)
{
final int NUM_EMPLOYEES = 3;
//creating array
int[] hours = new int[NUM_EMPLOYEES];
int[] employeeID = {5678459, 4520125, 7895122};
double[] payRate = new double[NUM_EMPLOYEES];
double[] wages = new double[NUM_EMPLOYEES];
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter your " + NUM_EMPLOYEES + " employees work hours and pay rate:");
//get the hours
for (int i = 0; i < NUM_EMPLOYEES; i++)
{
System.out.print("Employee #" + employeeID[i] + ": ");
hours[i] = keyboard.nextInt();
//get the hourly pay rate
System.out.print("Enter the pay rate: ");
payRate[i] = keyboard.nextDouble();
wages[i] = hours[i] * payRate[i];
}
//display wages
System.out.println("The hours and pay rates you entered are:");
for(int i = 0; i < NUM_EMPLOYEES; i++)
{
System.out.printf("The total wages for Employee #%d is $%.2f\n", employeeID[i], wages[i]);
}
}
}
You have 3 employees -> 3 wages.
But currently you're using only one variable to hold the wage: double wages = 0;
Hence its value is replaced for every loop.
You should create an array of length 3 to store the wages:
and in your loop, replace
wages = hours[i] * payRate;
With
wages[i] = hours[i] * payRate;
And print:
System.out.printf("The total wages for Employee #%d is $%.2f\n", employeeID[i], wages[i]);
You are setting the wage rate at each iteration. I.e. you are only ever recording a single state of wages. Then you are iterating and displaying that one wages variable, which will always be the last calculation.
Store each "wages" value in an array like you have done with hours and you should resolve your issue.
I just started coding in java and I am working on a change machine-esk program. I know It can be condensed but Its part of the constraints.
It keeps out putting random change owed and quarter count...
import java.util.Scanner;
public class Change {
public static void main(String[] args) {
double costVar, paidVar, amountOwed;//user defined
//defining the vale of US coins
final double quarterCoin = 0.25;
final double dimeCoin = 0.10;
final double nickelCoin = 0.05;
final double pennyCoin = 0.01;
//Variable for math stuff
double quarterAmountdec, dimeAmountdec, nickelAmountdec, pennyAmountdec;
short quarterAmountfin, dimeAmountfin, nickelAmountfin, pennyAmountfin;
Scanner keyboard = new Scanner(System.in);
//ask the user to input costs and amount payed (assuming the amount paid is > or = the cost of the item)
System.out.println("Enter Item Cost: ");
costVar=keyboard.nextDouble();
System.out.println("Enter Amount Paid: ");
paidVar=keyboard.nextDouble();
amountOwed = paidVar - costVar;//math for the changed owed
System.out.println("\nChange Owed: $" +amountOwed++);//displaying how much change the machine owes
//math to calculate the coins owed (involves intentional loss of accuracy
quarterAmountdec = amountOwed / quarterCoin;
quarterAmountfin = (short)quarterAmountdec;
//outputs coins owed
System.out.println("Quarters: " +quarterAmountfin++ );
}
}
Output:
Enter Item Cost:
2.34
Enter Amount Paid:
6.89
Change Owed: $4.55
Quarters: 22
The following line alters the amount owed after printing
System.out.println("\nChange Owed: $" +amountOwed++);
Thus when printing the amount owed looks fine, but internally the value is changed. I am personally unsure of the behaviour of calling ++ on a double, however I recommend removing the ++ and re-running your code.
I am new to Java and just now started with loops.
I have tried to do this exercise:
Write a program that lets the user enter the loan amount and loan period in number of years and displays the monthly and total payments for each interest rate starting from 5% to 8%, with an increment of 1/8.
So far this what i have got:
import java.util.Scanner;
public class compareLoansWithInterestRates {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.print("Loan Amount :");
int loan = input.nextInt();
System.out.print("Number of Years" );
int years = input.nextInt();
double monthPay, totalPay,interestRate;
System.out.println( "Interest Rate \t Monthly Payment \t Total Payment");
for(double rate =0.05; rate <=0.08; rate++ ){
for (int month = 1; month <= (years*12);month++){
rate +=1/8;
monthPay = loan* rate/(1-(Math.pow(1+rate,years*12)));
totalPay = monthPay*years*12;
interestRate= rate*100;
System.out.println("\t"+interestRate+" \t "+monthPay+"\t"+totalPay);
Why doesn't it work?
Just looking at your code briefly, you're incrementing rate within your 'outer for' loop using rate++ (which will increment by 1, not 0.01). You then increment rate again within the month loop by 1/8. Try removing 'rate++' from the outer loop. Not positive this will fix all your issues, but this is just a quick observation.
Where to start…
First of all: Java:
for(double rate =0.05; rate <=0.08; rate++ ){
this is good for int, not for double
rate +=1/8;
1/8 is much more then 0.125% you are looking for. It's not Java, but mathematics.
The second line should not be here at all, and for loop should be:
for(double rate =0.05; rate <=0.08; rate+=0.00125 ){
Unfortunately, your algorithm seems to be wrong too, so this change won't fix everything. But from Java point of view it will be rather ok.
I think this'll work
for (double i = 5; i <= 8; i += 0.125) {
double rate = i / 100;
monthPay = loan * (Math.pow(1 + (rate / 12), years * 12)) / 12;
totalPay = monthPay * years * 12;
interestRate = i;
System.out.println("\t" + interestRate + " \t " + monthPay + "\t" + totalPay);
}
I put together a simple loan calculator which is slightly different from yours, to show you just how much work goes into the input and output of a Java application.
Here's the input and output.
Loan Amount 60000
Number of Months 60
Yearly Interest Rate 6
Payments on a $60,000.00 loan for 60 months
Monthly Payment Total Payment
4.000% $1,104.99 $66,299.48
4.250% $1,111.77 $66,706.40
4.500% $1,118.58 $67,114.87
4.750% $1,125.41 $67,524.88
5.000% $1,132.27 $67,936.44
5.250% $1,139.16 $68,349.54
5.500% $1,146.07 $68,764.18
5.750% $1,153.01 $69,180.37
6.000% $1,159.97 $69,598.09
6.250% $1,166.96 $70,017.34
6.500% $1,173.97 $70,438.13
6.750% $1,181.01 $70,860.46
7.000% $1,188.07 $71,284.31
7.250% $1,195.16 $71,709.70
7.500% $1,202.28 $72,136.61
7.750% $1,209.42 $72,565.06
8.000% $1,216.58 $72,995.02
Here's the code that does the actual loan calculation to get the monthly amount.
private double calculateMonthlyPayment(double interestRate) {
double monthlyInterestRate = interestRate / 12D;
double numerator = (double) loanAmount * (monthlyInterestRate);
double denominator = Math.pow(1 + (monthlyInterestRate),
(double) -months);
denominator = 1D - denominator;
return numerator / denominator;
}
Pretty straightforward, right.
Now, I'm going to show you all of the code that gathered the input and produced the output. It's way longer than just the calculation. Go through the code as best you can, and I'll explain it as best I can.
package com.ggl.testing;
import java.text.NumberFormat;
import java.util.Scanner;
public class InterestRateCalculator implements Runnable {
private static final NumberFormat CF = NumberFormat.getCurrencyInstance();
private static final NumberFormat NF = NumberFormat.getNumberInstance();
private double interestRate;
private int loanAmount;
private int months;
#Override
public void run() {
getInputs();
produceOutputs();
}
public void getInputs() {
Scanner input = new Scanner(System.in);
System.out.print("Loan Amount ");
loanAmount = input.nextInt();
System.out.print("Number of Months ");
months = input.nextInt();
System.out.print("Yearly Interest Rate ");
interestRate = input.nextDouble();
input.close();
}
public void produceOutputs() {
double[] interestRates = new double[17];
double interestRate = this.interestRate - 2.0D;
for (int i = 0; i < interestRates.length; i++) {
interestRates[i] = interestRate / 100D;
interestRate += 0.25D;
}
String header = displayHeader();
System.out.println(" ");
System.out.println(header);
System.out.print(leftPad(" ", 10, ' '));
System.out.print(leftPad("Monthly Payment", 15, ' '));
System.out.println(leftPad("Total Payment", 15, ' '));
for (int i = 0; i < interestRates.length; i++) {
String s = displayInterestRate(interestRates[i]) + " ";
System.out.print(leftPad(s, 10, ' '));
double monthlyPayment = calculateMonthlyPayment(interestRates[i]);
System.out.print(leftPad(CF.format(monthlyPayment), 15, ' '));
double totalPayment = monthlyPayment * months;
System.out.print(leftPad(CF.format(totalPayment), 15, ' '));
System.out.println("");
}
}
private double calculateMonthlyPayment(double interestRate) {
double monthlyInterestRate = interestRate / 12D;
double numerator = (double) loanAmount * (monthlyInterestRate);
double denominator = Math.pow(1 + (monthlyInterestRate),
(double) -months);
denominator = 1D - denominator;
return numerator / denominator;
}
private String displayHeader() {
StringBuilder builder = new StringBuilder();
builder.append("Payments on a ");
builder.append(CF.format(loanAmount));
builder.append(" loan for ");
builder.append(NF.format(months));
builder.append(" months");
builder.append(System.getProperty("line.separator"));
return builder.toString();
}
private String displayInterestRate(double interestRate) {
return String.format("%.3f", interestRate * 100D) + "%";
}
private String leftPad(String s, int length, char padChar) {
if (s.length() > length) {
return s.substring(0, length);
} else if (s.length() == length) {
return s;
} else {
int padding = length - s.length();
StringBuilder builder = new StringBuilder(padding);
for (int i = 0; i < padding; i++) {
builder.append(padChar);
}
builder.append(s);
return builder.toString();
}
}
public static void main(String[] args) {
new InterestRateCalculator().run();
}
}
The first thing that I did was use the InterestRateCalculator class as a Java object. My static main method consists of one line.
new InterestRateCalculator().run();
This line does two things. It creates an instance of the InterestRateCalculator class and it executes the run method of the class.
It may seem strange now, but getting away from static methods and static fields allows you to create complex Java applications with many, many classes. You should learn this now, while you're writing simple applications.
I implemented Runnable because a Runnable class requires a run() method. It's a personal preference of mine. You could have named the run() method execute(), or some other meaningful name.
I didn't write a constructor. I used the default constructor of InterestRateCalculator();
Looking now at the run() method, I divided the problem into two parts. Reading or getting the input and producing the output. This allows me to focus on a smaller, simpler problem than the original problem. This is called divide and conquer.
Getting the input is straightforward. I copied your code and made the prompt text consistent. I added a space at the end of each prompt so the prompts and responses would look better. I know this sounds silly, but I assure you that I spent the better part of my programming career making changes to the appearance of the input and output of applications.
Getting the output to line up took a large part of the code to produce the output. Producing the output was more complicated than gathering the input. I broke the process down into many methods. A method should do one thing, and return one output, like the calculateMonthlyPayment I showed you earlier.
I used a trick that I learned in the olden times of Cobol programming to produce the output. I left padded the Strings I created with spaces. You don't have to memorize this particular trick. Other "tricks" have been gathered together and called design patterns. Don't worry about learning any patterns right now. Just know that they exist so that you can group code into higher levels.
I hope this explanation was helpful to you. I know you wanted to write the code yourself. That's why I solved a different problem than yours.
monthpay is incorrect
monthPay = loan* rate/(1-1/(Math.pow(1+rate,years*12)))