Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
So I am creating a future value application, that allows the user to enter the amount they have invested, the percent per year, how many years it is invested, and if it is compounded annually, semi-annually, monthly, daily, etc.
The problem I am having is that my answer is turning out wrong, but only by a couple hundreds.
With the code I have now, I am using the example for Semi-Annually:
PV = 1000
Interest Rate = 3
Years Invested = 10
Compounded = Semi Annually
The answer I get is 1806.
The correct answer is 1346.86, supposedly.
The code I have is here:
public void actionPerformed(ActionEvent event)
{
String input1 = textInitialAmount.getText();
String input2 = textAnnualInterest.getText();
String input3 = textNumberOfYears.getText();
String comp = textCompounded.getText();
double invest = Double.parseDouble(input1);
double interest = Double.parseDouble(input2);
double numberofyear = Double.parseDouble(input3);
if(comp.equals("Annually"))
{
double compPeriod = 1;
double compNumberOfYear = numberofyear * compPeriod;
double rate = (interest / 100) + 1;
double valueFuture = invest * Math.pow(rate, compNumberOfYear);
String output = String.format("%5.0f", valueFuture);
futureValue.setText("The future value is " + output);
}
if (comp.equals("Semi-Annually"))
{
double compPeriod = 2;
double compNumberOfYear = compPeriod * numberofyear;
double percentRate = interest / 100;
double rate = percentRate + 1;
double valueFuture = invest * Math.pow(rate, compNumberOfYear);
String output = String.format("%5.0f", valueFuture);
futureValue.setText("The future value is " + output);
}
if(comp.equals("Monthly"))
{
double compPeriod = 12;
double compNumberOfYear = compPeriod * numberofyear;
double rate = 1 + (interest / 100);
double valueFuture = invest * Math.pow(rate, compNumberOfYear);
String output = String.format("%5.0f", valueFuture);
futureValue.setText("The future value is " + output);
}
if(comp.equals("Bi-Weekly"))
{
}
}
}
Thanks for the help. Please comment if you need me to explain more.
Your problem is not related to coding... it's related to the way you're dealing with interest rates!
If you compound the interest Annually, you have 1 conversion period per year.
If you compound the interest Biannually (or "Semiannually" as your question says), you have 2 periods per year, and you have to convert the interest rate to an efective Biannual interest rate before computing the interest.
The correct code would be something like this:
double compPeriod = 2;
double compNumberOfYear = compPeriod * numberOfYear;
double percentRate = (interest / compPeriod) / 100;
// ^^^^^^^^^^^^^^^^^^^^^
// You missed this!
double rate = percentRate + 1;
double valueFuture = invest * Math.pow(rate, compNumberOfYear);
Do it by hand:
Interest rate: 3%
Compound periods: 2
Years: 10
Periods: 2 * 10 = 20
Efective interest rate: 3% / 2 = 1.5%
Investment: 1000
Future value: 1000 * (1 + 0.015)^20 = 1346.85500655
A little gift: Cleaner and simpler code (Because I'm a nice guy ;) )
You're aufully duplicating your code! You can clean it up:
public void actionPerformed(ActionEvent event) {
String input1 = textInitialAmount.getText();
String input2 = textAnnualInterest.getText();
String input3 = textNumberOfYears.getText();
String comp = textCompounded.getText();
double invest = Double.parseDouble(input1);
double interest = Double.parseDouble(input2);
double numberofyear = Double.parseDouble(input3);
// You just need to declare variables once!
double compPeriod;
switch(comp.toLowerCase()) {
case "annually":
compPeriod = 1;
break;
case "semiannually":
compPeriod = 2;
break;
case "monthly":
compPeriod = 12;
break;
case "bi-weekly":
compPeriod = 26; // Assuming 52 weeks per year
break;
case "weekly":
compPeriod = 52; // Assuming 52 weeks per year
break;
default:
compPeriod = 1;
}
double compNumberOfYear = numberofyear * compPeriod;
double valueFuture = invest * Math.pow(1 + (interest / compPeriod) / 100, compNumberOfYear);
String output = String.format("%5.0f", valueFuture);
futureValue.setText("The future value is " + output);
}
}
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
Why is the last calculation printing out the wrong calculation.
here is my code:
System.out.print("Enter total cost: ");
double totalCost = input.nextDouble();
System.out.print("The Customer has paid: ");
double customerAmount = input.nextDouble();
//Calculations
double changeOwed = customerAmount - totalCost;
System.out.println("Change owed: $"+(int)changeOwed);
int amountFifty = (int)changeOwed/50;
System.out.println("How many $50 notes = " +amountFifty);
int takeAway = (int)changeOwed - (amountFifty * 50);
int amount20 = takeAway / 20;
System.out.println("How many $20 notes = " +amount20);
int amount10 = (takeAway - amount20*20) / 10;
System.out.println("How many $10 notes = " +amount10);
enter code here
int amount5 = (takeAway - amount10*10) / 5;
System.out.println("How many $5 notes = " +amount5);
int amount2 = (takeAway - amount5*5) / 2;
System.out.println("How many $2 notes = " +amount2);
int amount1 = (takeAway - amount2*2) /1;
System.out.printl
n("How many $1 notes = " +amount1);
You are not keeping track of the change you have issued along the way correctly.
int takeAway = (int)changeOwed - (amountFifty * 50);
The line above correctly calculates what's left after you determine the number of $50 bills required. This means that:
int amount20 = takeAway / 20;
int amount10 = (takeAway - amount20*20) / 10;
correctly calculates the number of $10 and $20 bills.
int amount5 = (takeAway - amount10*10) / 5;
is incorrect because you do do not subtract the values of the $20 bills, only the $10 bills. You make a similar error calculating the $2, ie. you do not account for $20 and $10. The error compounds for the $1.
You could try something like:
int amountFifty = changeOwed / 50;
double takeAway = changeOwed - (amountFifty * 50);
int amount20 = takeAway / 20;
takeAway -= (amount20 * 20);
int amount10 = takeAway / 10;
takeAway -= (amount10 * 10);
int amount5 = takeAway / 5;
takeAway -= (amount5 * 5);
int amount2 = takeAway / 2;
takeAway -= (amount2 * 2);
int amount1 = takeAway / 1;
my assignment is to calculate the number of years it takes to reach $5000 if you start with $2500 with 7.5% interest. The calculation should be 10 years, but it outputs 11 years. This might be a simple syntax error, but I've been trying to fix this for the past 2 hours with no luck.
final double principle = 2500.00;
double accrued = 0;
final double interest = 0.075;
int year = 0;
double interest1 = 1.0 + interest;
while (accrued < 5000.00)
{
accrued = principle * Math.pow(interest1, year);
year++;
}
System.out.printf("It would take %d years to reach at least $5000 if you start with $2,500 with 7.5%% compound interest.", year);
Try this :
final double principle = 2500.00;
double accrued = 0;
final double interest = 0.075;
int year = 0;
double interest1 = 1.0 + interest;
while (accrued < 5000.00)
{
year++;
accrued = principle * Math.pow(interest1, year);
}
System.out.printf("It would take %d years to reach at least $5000 if you start with $2,500 with 7.5%% compound interest.", year);
I'm making a program for my java class 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). I currently have this code.
int startYear = 2011;
int endYear = user_input.nextInt();
double t = 1.2; //Population percent increase anually
double nbr = (endYear - startYear); //Number of years increased
double pStart = 7.000; //Starting population of 2011
double pEnd = pStart * Math.exp(nbr * t); // Ending population of user input
DecimalFormat nf = new DecimalFormat("2");
System.out.println("Population in " + endYear + ": " (nf.format(pEnd)));
There's no errors in the code, everything works, but I'm having troubles with the pEnd equation. Currently when I enter 2016 for the end year, i get 22824. I've tried googling a formula, but i can't find anything. Do any of you guys have an idea of the formula? If you enter 2016 for the end year, it should be around 7.433
You're incrementing by a factor of 1.2, which would represent 120% instead of 1.2%. I think what you want is :
double t = 0.012;
This change gives me an exact value of 7.4328558258175175 from 2011 to 2016.
EDIT : here's the code as requested by the author :
public static void main(String args[]){
int startYear = 2011;
int endYear = 2016;
double t = 0.012; //Population percent increase anually
double nbr = (endYear - startYear); //Number of years increased
double pStart = 7.000; //Starting population of 2011
double pEnd = pStart * Math.exp(nbr * t); // Ending population of user input
System.out.println("Population in " + endYear + ": " + pEnd);
}
Use Math.pow(1 + t / 100, nbr) instead of Math.exp(nbr * t) because you need (1+t/100)^nbr (i.e. multiply 1 + t / 100 on itself nbr times), not exp^(nbr*t):
double pEnd = pStart * Math.pow(1 + t / 100, nbr); // Ending population of user input
Try this.
double pEnd = pStart * Math.pow(1.0 + t / 100, nbr);
Right now I am finding out 25% of a persons years and for example if you had 5 years 25% is 1.25. Though the plugin im making cant remove 1.25 years from you the .25 needs to be converted to weeks and then any leftovers to days and so on. Though I dont know how I would convert these times.
Integer y = itapi.getPlayerYears(player.getName());
Double yremove = Integer.valueOf(y) * 0.25;
Integer w = itapi.getPlayerWeeks(player.getName());
Double wremove = Integer.valueOf(w) * 0.25;
Integer d = itapi.getPlayerDays(player.getName());
Double dremove = Integer.valueOf(d) * 0.25;
Integer h = itapi.getPlayerHours(player.getName());
Double hremove = Integer.valueOf(h) * 0.25;
Integer m = itapi.getPlayerMinutes(player.getName());
Double mremove = Integer.valueOf(m) * 0.25;
Integer s = itapi.getPlayerSeconds(player.getName());
Double sremove = Integer.valueOf(s) * 0.25;
String yminus = String.valueOf(yremove) + 'y';
String wminus = String.valueOf(wremove) + 'w';
String dminus = String.valueOf(dremove) + 'd';
String hminus = String.valueOf(hremove) + 'h';
String mminus = String.valueOf(mremove) + 'm';
String sminus = String.valueOf(sremove) + 's';
ItemStack book = itapi.createTimeCard("Death of " + player.getName(), yminus + wminus + dminus + hminus + mminus + sminus, 1);
itapi.removeTime(player.getName(), yminus + wminus + dminus + hminus + mminus + sminus );
e.getDrops().add(book);
Would it be possible to work the conversion out or would it be better to convert all time to seconds then take 25% and convert it back?
I would use nested ifs and pass the remainder around. I have not tested this but it should give you an idea.
Integer y = itapi.getPlayerYears(player.getName());
double yremove = Integer.valueOf(y) *0.25;
double numWeeks = yremove * 52; //returns the number in weeks
double numDays =0;
double numHours =0;
double numMinutes =0;
double numSeconds =0;
if(numWeeks % 52 != 0){
numDays = (numWeeks % 52) * 7;
if(numDays % 7 !=0){
numHours = (numDays % 7) * 24;
if(numHours % 24 !=0){
numMinutes = (numHours % 24) * 60;
if(numMinutes % 60 !=0){
numSeconds = (numMinutes % 60) * 60;
}
}
}
}
//... then convert to string as you are already doing and pass it to removeTime()
You can use Calendar class to calculate this for you, something like:
Calendar c = Calendar.getInstance();
double millis = 1.25 * 31557600 * 1000;
long l = (long) millis;
c.setTimeInMillis(l);
System.out.println(c.get(Calendar.YEAR) + " Year");
System.out.println(c.get(Calendar.MONTH) + " months");
System.out.println(c.get(Calendar.WEEK_OF_MONTH) + " weeks");
System.out.println(c.get(Calendar.DAY_OF_MONTH) + " days");
System.out.println(c.get(Calendar.HOUR) + " hours");
System.out.println(c.get(Calendar.MINUTE) + " minutes");
System.out.println(c.get(Calendar.SECOND) + " seconds");
Output:
1971 Year
3 months
1 weeks
2 days
7 hours
0 minutes
0 seconds
Calendar defaults the starting year to 1970, you can further manipulate year and months to weeks if need be.
Create a class to manage time. This class will have methods to return time in terms of years, weeks, months, etc.
public class Time{
private long milliseconds;
public double getSeconds(){
double seconds = milliseconds/1000.0;
return seconds;
}
public void subtractSeconds(double seconds){
long millisInSeconds = (long)(seconds*1000);
this.millisecionds -= millisInSeconds;
}
//write more methods for years, months etc.
}
Then, use this class to retrieve years, months, weeks and subtract the difference. This will keep your code clean, and easy to understand.
Time time = new Time(1000*60*60);
int years = (int)time.getYears();
time.subtractYears(years);
int months = (int)time.getMonths();
time.subtractMonths(months);
I have to make this GUI that is a CD calculator.
I put in the Initial investment ($): e.g. 2000
the Annual interest rate (%): e.g. (8%)
Ending value ($): e.g. 5000
The program then outputs on a jLabel: The amount of years required are "12" (e.g.)
I need to make a do while loop and a counter.
I did the get text from the 3 text fields then add the initialInvestment with the annual rate % but having trouble with the loop and the counter?
int initialInvestment, endValue, cdvalue;
double cdValue, annualDecimalConvert, annualRate;
initialInvestment = Integer.parseInt(initialInvestmentInput.getText());
annualRate = Double.parseDouble(interestRateInput.getText())/100;
endValue = Integer.parseInt(endingValueInput.getText());
cdValue = initialInvestment + (initialInvestment * annualRate);
double a = cdValue;
while (a <= endValue){
a = a++;
yearsOutput.setText("The required year needed is: " + a);
}
You're simply adding 1 to a every iteration of the loop. So it'll take a few thousand iterations that way to fullfil the loop requirements.
What you have to do is keep adding the interest every year while keeping count of the years and only update the output after you're done looping.
int initialInvestment, endValue;
double cdValue, annualDecimalConvert, annualRate;
initialInvestment = Integer.parseInt(initialInvestmentInput.getText());
annualRate = Double.parseDouble(interestRateInput.getText())/100;
endValue = Integer.parseInt(endingValueInput.getText());
// First year interest is counted here.
cdValue = initialInvestment + (initialInvestment * annualRate);
int years = 1;
while (cdValue < endValue){
cdValue = cdValue + (cdValue * annualRate);
years++;
}
yearsOutput.setText("The required year needed is: " + years);