DecimalFormat Division - java

double mny = 0;
mny = Double.parseDouble(JOptionPane.showInputDialog(null, "Enter the amount of Money", "Money Input", JOptionPane.QUESTION_MESSAGE));
//Check for Tens
System.out.println("The # of Tens is " + (int)(mny/10));
mny = mny%10;
System.out.println("The remaining amount of money is " + new DecimalFormat("0.00").format(mny) + " $ ");
//Check for Fives
System.out.println("The # of Fives is " + (int)(mny/5));
mny = mny%5;
System.out.println("The remaining amount of money is " + new DecimalFormat("0.00").format(mny) + " $ ");
//Check for Pennies
System.out.println("The # of Pennies is " + (int)(mny/0.01));
mny = mny%0.01;
System.out.println("The remaining amount of money is " + new DecimalFormat("0.00").format(mny) + " $ ");
If I input 0.01 it gives me 1 penny, but if I input 15.01 it gives me 1 ten 1 five but no penny.
How should I solve this problem?

The issue you see is why it is highly discouraged to use double for monetary values. Use BigDecimal instead.
public static void printCoins(double mny) {
BigDecimal amount = BigDecimal.valueOf(mny);
//Check for Tens
BigDecimal[] quotientAndRemainder = amount.divideAndRemainder(BigDecimal.TEN);
BigDecimal tens = quotientAndRemainder[0].setScale(0);
amount = quotientAndRemainder[1];
System.out.println("The # of Tens is " + tens);
System.out.println("The remaining amount of money is " + amount.setScale(2, RoundingMode.HALF_EVEN) + " $ ");
//Check for Fives
quotientAndRemainder = amount.divideAndRemainder(BigDecimal.valueOf(5));
BigDecimal fives = quotientAndRemainder[0].setScale(0);
amount = quotientAndRemainder[1];
System.out.println("The # of Fives is " + fives);
System.out.println("The remaining amount of money is " + amount.setScale(2, RoundingMode.HALF_EVEN) + " $ ");
//Check for Pennies
quotientAndRemainder = amount.divideAndRemainder(BigDecimal.valueOf(0.01));
BigDecimal pennies = quotientAndRemainder[0].setScale(0);
amount = quotientAndRemainder[1];
System.out.println("The # of Pennies is " + pennies);
System.out.println("The remaining amount of money is " + amount.setScale(2, RoundingMode.HALF_EVEN) + " $ ");
}
Tests
printCoins(0.01);
printCoins(15.01);
Output
The # of Tens is 0
The remaining amount of money is 0.01 $
The # of Fives is 0
The remaining amount of money is 0.01 $
The # of Pennies is 1
The remaining amount of money is 0.00 $
The # of Tens is 1
The remaining amount of money is 5.01 $
The # of Fives is 1
The remaining amount of money is 0.01 $
The # of Pennies is 1
The remaining amount of money is 0.00 $

The problem you have hit is that floating point number representation is imprecise.
The simplest and easiest way of handling currency is to work with pennies, which are always a whole number, so you can calculate everything using int variables.
This is how banks handle purchase transaction data.
Start with converting user input to an integer number of pennies:
double input = Double.parseDouble(JOptionPane.showInputDialog(null, "Enter the amount of Money", "Money Input", JOptionPane.QUESTION_MESSAGE));
int pennies = (int)(input * 100);
Then the rest of your code needs to be converted to working with pennies, which is straightforward.

Because you are assigning the result of each comparison to mny variable, try without them:
double mny = 0;
mny = Double.parseDouble(JOptionPane.showInputDialog(null, "Enter the amount of Money", "Money Input", JOptionPane.QUESTION_MESSAGE));
//Check for Tens
System.out.println("The # of Tens is " + (int)(mny/10));
System.out.println("The remaining amount of money is " + new DecimalFormat("0.00").format(mny % 10) + " $ ");
//Check for Fives
System.out.println("The # of Fives is " + (int)(mny/5));
System.out.println("The remaining amount of money is " + new DecimalFormat("0.00").format(mny % 5) + " $ ");
//Check for Pennies
System.out.println("The # of Pennies is " + (int)(mny/0.01));
System.out.println("The remaining amount of money is " + new DecimalFormat("0.00").format(mny % 0.01) + " $ ");

Related

Rising tuition cost after ten years

Suppose that the tuition for a university is $10,000 this year and increases 5% every year. In one year, the tuition will be $10,500. Write a program that computes the tuition in ten years and the total cost of four years' worth of tuition after the tenth year.
I can calculate the tenth year tuition easily enough. What has me stumped is how to add the unique tuition values at years 11, 12, 13 and 14.
double Fee = 10000;
double Year = 1;
double TotalFee;
double Rate = 5;
double TotalCost = 15000 + 15500 + 16000 + 16500;
System.out.println("Year " + " Total Fee ");
System.out.println();
while (Year <= 14) {
TotalFee = Fee + ((Fee * ((Year * Rate) - Rate)) / 100);
System.out.println(Year + " " + " "+ TotalFee);`
Year++;
}
System.out.println("Total cost tuition of 4 years starting 10 years from now is " + TotalCost);
The last while loop is my attempt at adding the 4 years. How could I pull out the unique values of TotalCost at iterations 11 to 14 and add them?
Since you want to increase the amount 5% every year, instead of having rate = 5
You should have rate = 1.05.
With the rate as 1.05 you can do this
FeeAtYear1 = 10000*1.05^0 = 10000
FeeAtYear2 = 10000*1.05^1 = 10500
FeeAtYear3 = 10000*1.05^2 = 11025
FeeAtYear4 = 10000*1.05^3 = 11576.25
...
FeeAtYear10 = 10000*1.05^9 = ~16288.95
You don't even need a while loop.
TotalCost = 10000 *1.05^10 + 10000 *1.05^11 + 10000 *1.05^12 + 10000 *1.05^13;

Trying to make a while loop work properly

I'm making a program that calculates the population for a year given the start year (2011) and increases the population by 1.2% every year. The population for 2011 is 7.000 (I'm using decimals, instead of billions). Here is the working part of my code
package src;
import java.util.Scanner;
import java.text.DecimalFormat;
public class Demographics {
public static void main(String[] args) {
Scanner user_input= new Scanner(System.in);
//Part 1
System.out.println("===--- Part 1 ---===");
System.out.println("Population in 2011: 7.000");
System.out.print("What is the desired year? ( > 2011) ");
int startYear = 2011;
int endYear = user_input.nextInt();
while (endYear <= startYear){
System.out.println("Invalid end year.");
System.out.print("What is the desired year? ( > 2011) ");
endYear = user_input.nextInt();
break;
}
double t = 0.012;
double nbr = (endYear - startYear);
double pStart = 7.000;
double pEnd = pStart * Math.exp(nbr * t);
DecimalFormat nf = new DecimalFormat("#.000");
System.out.println("Population in " + endYear + ":(nf.format(pEnd)));
//Part 2
System.out.println("===--- Part 2 ---===");
System.out.print("What is the target population? ( > 7.000) ");
double pTarget = user_input.nextDouble();
while (pTarget <= pStart){
System.out.println("Invalid target population.");
System.out.print("What is the target population? ( > 7.000) ");
pTarget = user_input.nextDouble();
break;
}
while (pStart < pTarget){
startYear++;
pStart = pStart + (pStart * 0.012);
System.out.println("Population in " + startYear + ": " + nf.format((pStart)));
}
}
}
Part 1 of my code calculates the population of a year when the user enters it, then part 2 shows the calculations of how many years it will take when a user enters a population to get to that point.
Here is the code that doesn't work
//Part 3
System.out.println("===--- Part 3 ---===");
t = 1.2;
pStart = 7.000;
pEnd = pStart * Math.exp(nbr * t);
while (pStart < pTarget){
startYear++;
pEnd = pStart + (pStart * 0.012);
if (pEnd >= pStart * 2 ){
System.out.println("Population in " + startYear + ": " + nf.format((pEnd)) + " Population growth rate " + ": " + (t / 2));
}else{
System.out.println("Population in " + startYear + ": " + nf.format((pEnd)) + " Population growth rate " + ": " + t);
}
}
Currently when i have part 3 in my code it does an infinite loop without multiplying the population. What I'm trying to do in part 3 is pretty much the same thing in part 2, but in part 3 it will display the population growth rate (t) and divide it by 2 every time the population doubles. For example:
Population in 2019 : 7.705 ; population growth rate : 1.2%
Population in 2020 : 7.798 ; population growth rate : 1.2%
Population in 2021 : 7.892 ; population growth rate : 1.2%
...
Population in 2068 : 13.873 ; population growth rate : 1.2%
Population in 2069 : 14.040 ; population growth rate : 0.6%
Anyone have any ideas on how to achieve this?
if you have problems in the loop the reason is in the condition!
while (pStart < pTarget){
so to end this code, inside the loop one of this situation has to happen:(according with your condition)
A)pStart should increase in value
B)pTarget should decrement in value
C)a "break;" have to occur
in your code you increase: startYear and pEnd, but this are not the condition to close the loop according with your condition. (i write it before:A,B,C)
1) also startYear are not re initialize it before the loop, and start already at a high value. you have to add bedore the loop:
startYear = 2011;
2) you should as far as possible to create new variables for the segment 3, is not to have problems like the one just described, is to be clear about what you are doing.
my advice for part three is this:
(Considering that I have no clear what I wanted to do reading your code, you have to cange it and make it good for you)
System.out.println("===--- Part 3 ---===");
t = 1.2;
startYear = 2011; // I add it
double pEveryYear = 7000;
while (pEveryYear < pTarget){
startYear++;
pEveryYear = pEveryYear + (pEveryYear * 0.012);
if (pEveryYear >= pTarget ){ // this condition cange only the print in the console
System.out.println("Population in " + startYear + ": " + nf.format((pEveryYear)) + " Population growth rate " + ": " + (t / 2));
break; // if you write it before the system.out you can't read it in the console.
}else{
System.out.println("Population in " + startYear + ": " + nf.format((pEveryYear)) + " Population growth rate " + ": " + t);
}
}
}
this the console output for input like "8000":
===--- Part 3 ---===
Population in 2012: 7084.000 Population growth rate : 1.2
Population in 2013: 7169.008 Population growth rate : 1.2
Population in 2014: 7255.036 Population growth rate : 1.2
Population in 2015: 7342.097 Population growth rate : 1.2
Population in 2016: 7430.202 Population growth rate : 1.2
Population in 2017: 7519.364 Population growth rate : 1.2
Population in 2018: 7609.596 Population growth rate : 1.2
Population in 2019: 7700.912 Population growth rate : 1.2
Population in 2020: 7793.323 Population growth rate : 1.2
Population in 2021: 7886.842 Population growth rate : 1.2
Population in 2022: 7981.485 Population growth rate : 1.2
Population in 2023: 8077.262 Population growth rate : 0.6
It seems you have two variables in the while loop that you try to compare however these do not actually get updated while iterating in the while loop. So after every iteration within the loop, the while condition just stays true.
See the last few lines below for a minor change to your part 3 code :
System.out.println("===--- Part 3 ---===");
t = 1.2;
pStart = 7.000;
pEnd = pStart * Math.exp(nbr * t);
while (pStart < pTarget){
startYear++;
pEnd = pStart + (pStart * 0.012);
if (pEnd >= pStart * 2 ){
System.out.println("Population in " + startYear + ": " + nf.format((pEnd)) + " Population growth rate " + ": " + (t / 2));
} else {
System.out.println("Population in " + startYear + ": " + nf.format((pEnd)) + " Population growth rate " + ": " + t);
}
pStart = startYear; // <-- NEW, you can probably use pStart instead of startYear in this code
}
The only missing thing I see in your code is that you are not updating pStart every time you go through the loop. This will not only make your loop infinite but it's also doing a wrong calculation every time except the first iteration. I added only one line from your code:
System.out.println("===--- Part 3 ---===");
t = 1.2;
pStart = 7.000;
pEnd = pStart * Math.exp(nbr * t);
while (pStart < pTarget){
startYear++;
pEnd = pStart + (pStart * 0.012);
if (pEnd >= pStart * 2 ){
System.out.println("Population in " + startYear + ": " + nf.format((pEnd)) + " Population growth rate " + ": " + (t / 2));
}else{
System.out.println("Population in " + startYear + ": " + nf.format((pEnd)) + " Population growth rate " + ": " + t);
}
pStart = pEnd;
}

Electricity/Energy Bill Calculator: Java

I am having issues figuring out exactly what is wrong with this little Electricity/Energy calculator used to calculate computer energy costs.
I'd appreciate any help.
Program:
import java.util.Scanner;
public class ElectricityCalculations {
public static void main (String [] args) {
Scanner scnr = new Scanner(System.in);
double usageHoursPerDay = 0; // Hours computer is on per day
double usageDaysPerWeek = 0; // Days computer is used per week
double usageWeeksPerYear = 0; // Weeks computer is used per year
double wattsPerHour = 0; // Watts used by computer per hour
final double COST_PER_KWH = 0.145; // Prices of power per kilowatt hour
final double LBS_CO2_PER_KWH = 0.58815; // Pounds of CO2 generated per KWH
double usageHoursPerYear = 0; // Amount of hours on per year
double usageWattHoursPerYear = 0; // Amount of watt hours consumed per year
double usageKWHPerYear = 0; // Amount of KWH used in a year
double costPerYear = 0; // Total cost per year
double lbsCO2PerYear = 0; // Total amount of CO2 in pounds released per year
// Input Values
System.out.println("How many hours is your computer on per day?");
usageHoursPerDay = scnr.nextDouble();
System.out.println("How many days per week is your computer used?");
usageDaysPerWeek = scnr.nextDouble();
System.out.println("How many weeks per year is your computer used?");
usageWeeksPerYear = scnr.nextDouble();
System.out.println("How many watts per hour does your computer use? (Suggestive value for desktop: 100, laptop: 30).");
wattsPerHour = scnr.nextDouble();
// Calculations
usageHoursPerYear = usageHoursPerDay * 365;
usageWattHoursPerYear = wattsPerHour * 8760; // 8760 is the number of hours in a year
usageKWHPerYear = usageWattHoursPerYear / 1000;
costPerYear = usageKWHPerYear * COST_PER_KWH;
lbsCO2PerYear = LBS_CO2_PER_KWH * usageKWHPerYear;
// Printing Energy Audits
System.out.println("Computer Energy Audit");
System.out.println("You use your computer for " + usageHoursPerYear + " hours per year.");
System.out.println("It will use " + usageWattHoursPerYear + " KWH/year.");
System.out.println("Whih will cost " + costPerYear + "$/year for electricity.");
System.out.println("Generating that electricity will produce " + lbsCO2PerYear + " lbs of CO2 pollution.");
return;
}
}
Inputs:
8 hours/day
5 days/week
50 weeks/year
100 watts/hour
My (wrong output):
Computer Energy Audit:
You use your computer for 2920.0 hours per year.
It will use 876000.0 KWH/year.
Whih will cost 127.02$/year for electricity.
Generating that electricity will produce 515.2194 lbs of CO2 pollution.
Correct Output:
Computer Energy Audit:
You use your computer for 2000.0 hours per year.
It will use 200.0 KWH/year.
Which will cost 28.999999999999996 $/year for electricity.
Generating that electricity will produce 117.63 lbs of CO2 pollution.
You take in the number of days per week and weeks per year as input, but forget to use them in your calculations. Also, instead of printing KWH, you are displaying the variable storing Watt Hours.
// Calculations
usageHoursPerYear = usageHoursPerDay * usageDaysPerWeek * usageWeeksPerYear; //calculate based on time used, not 365 days in the year
usageWattHoursPerYear = wattsPerHour * usageHoursPerYear; //use variable from above line
usageKWHPerYear = usageWattHoursPerYear / 1000;
costPerYear = usageKWHPerYear * COST_PER_KWH;
lbsCO2PerYear = LBS_CO2_PER_KWH * usageKWHPerYear;
// Printing Energy Audits
System.out.println("Computer Energy Audit");
System.out.println("You use your computer for " + usageHoursPerYear + " hours per year.");
System.out.println("It will use " + usageKWHPerYear + " KWH/year."); //changed to correct variable
System.out.println("Whih will cost " + costPerYear + "$/year for electricity.");
System.out.println("Generating that electricity will produce " + lbsCO2PerYear + " lbs of CO2 pollution.");

coins output in vending maching? [duplicate]

This question already has answers here:
Java program that tells what coins to give out for any amount of change from 1 cent to 99 cents
(3 answers)
Closed 7 years ago.
I'm not sure where I'm wrong. I am not being able to get the proper output as expected. Below is my piece of program:
public static void insertMoney(){
double dollars, quarters, dimes, nickels, pennies;
double paymentSum=0;
System.out.println("Enter amount of money in cents.");
Scanner input = new Scanner(System.in);
paymentSum = input.nextDouble();
//paymentSum = (paymentSum)/100;
if (paymentSum <= 0){
System.out.println("Please feed me more money, so I can feed you!. Try again next time :)");
return;
}
System.out.println("You entered: " +paymentSum+" Cent(s).");
System.out.println((paymentSum/100) + " Cent(s) in coins can be given as: ");
dollars = paymentSum /100;
paymentSum = paymentSum%100;
quarters = paymentSum/25;
paymentSum = paymentSum % 25;
dimes = paymentSum/10;
paymentSum = paymentSum % 10;
nickels = paymentSum/5;
paymentSum = paymentSum % 5;
pennies = paymentSum;
System.out.println(dollars + " dollar(s)");
System.out.println(quarters + " quarter(s)");
System.out.println(dimes + " dime(s)");
System.out.println(nickels + " nickel(s) and");
System.out.println(pennies + " pennies");
}
I'm trying to get output as this:
You entered: 26.0 Cent(s).
0.26 Dollar(s) in coins can be given as:
0.0 dollar(s)
1.0 quarter(s)
0.0 dime(s)
0.0 nickel(s) and
1.0 pennies
But I get this:
You entered: 26.0 Cents(s).
0.26 Dollar(s) in coins can be given as:
0.26 dollar(s)
1.04 quarter(s)
0.1 dime(s)
0.2 nickel(s) and
1.0 pennies
What am I doing wrong in my code? Any help would be appreciated. Thanks!
The problem is your expecting integer division but using a double paymentSum.
As noted in this article, since paymentSum is a double, any division will also produce a double. That's why your quarters are showing up as 1.04 instead of 1, and why your dimes are 0.1 instead of 0, etc...

Use output as an input on the next loop

I need to have an outcome like this:
example the user input are principal = 2000, term=6, rate=2%
Period Interest Total Interest Total Balanced<br>
1 6.66 6.66 2006.60
2 6.69 13.35 2013.35
3 6.71 20.06 2020.06
4 6.74 26.80 2026.80
5 6.75 33.55 2033.55
6 6.78 40.33 2040.33
My code is:
import java.io.*;
public class interest
{
public static void main(String[] args)throws Exception
{
BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(System.in));
float p, t, r, total;
int a = 1;
System.out.println("Enter the amount deposited: ");
p = Integer.parseInt(bufferedreader.readLine());
System.out.println("Enter the number of term: ");
t = Integer.parseInt(bufferedreader.readLine());
System.out.println("Enter the interest rate(%): ");
r = Integer.parseInt(bufferedreader.readLine());
System.out.println("Period \t Interest Total Interest Total Balance");
while ( a <= t)
{
System.out.print(" " + a + "\t ");
a++;
{
float R = (float) (r/100)/t;
float interest = (float) p * R;
float totalInt = (float) interest ;
total = p + totalInt;
System.out.println(interest + "\t\t" + totalInt + "\t " + total);
}
}
}
}
but the outcome turns up like this:
Period Interest Total Interest Total Balance
1 6.6666665 6.6666665 2006.6666
2 6.6666665 6.6666665 2006.6666
3 6.6666665 6.6666665 2006.6666
4 6.6666665 6.6666665 2006.6666
5 6.6666665 6.6666665 2006.6666
6 6.6666665 6.6666665 2006.6666
Move your totalInt declaration outside of your while declaration.
You're currently resetting it in every loop, thus it's not actually your total interest but your current interest.
You need to do: totalInt += interest; in the loop.
And you don't need to cast interest to a float again for the increment, as it's already declared as a float.
Also it might be cleaner to do total += interest rather than starting out from your base deposit and incrementing it with your totalInt every time.
And as to your last issue, the formatting, just do something along the lines of:
System.out.printf("%.2f \t\t %.2f \t\t %.2f\n", interest, totalInt, total);
Or take a look at DecimalFormat
I am assuming the question is about the output formating
System.out.printf("%.2f \t\t %.2f \t\t %.2f\n", interest, totalInt, total);
Hi keep float interest before while loop like this
float interest=0;
while ( a <= t)
{
System.out.print(" " + a + "\t ");
a++;
{
float R = (float) (r/100)/t;
interest = interest + (float) p * R;
float totalInt = (float) interest ;
total = p + totalInt;
System.out.println(interest + "\t\t" + totalInt + "\t " + total);
}
}
}
Now Execute it you will get the required output please like if you are satisfied.
Thank You
I think what you want is, change the first line to:
float p, t, r, total, R, interest, totalInt;
and remove float declaration inside loop

Categories

Resources