Ok so this java program I'm working on is supposed to compute an investment value over the course of 30 years. It asks the user where their starting investment is and the percentage rate (in the form of decimals). I thought I had it all figured out but my program is returning some ridiculous values. Can someone take a look at my code and tell me what I did wrong?
These are the sample outputs provided to me
What is the amount invested? 1000
What is the annual interest rate? .09
Years Future Value
----- ------------
1 $1093.81
2 $1196.41
...
29 $13467.25
30 $14730.58
my output is returning values in billions and trillions of dollars...just crazy stuff. The formula I have been provided with is
futureValue = investmentAmmount * (1 + monthlyInterestRate)^numberOfYears*12
here is the code for my program
import java.util.Scanner;
import java.text.NumberFormat;
import java.util.Locale;
import java.text.DecimalFormat;
public class InvestmentValue
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
NumberFormat df = DecimalFormat.getCurrencyInstance(Locale.US);
double investmentAmmnt;
// monthly interest rate
double mri;
int years;
System.out.print("What is the ammount invested? ");
investmentAmmnt = input.nextDouble();
System.out.print("What is the annual interest rate? ");
mri = input.nextDouble();
futureInvestmentValue(investmentAmmnt, mri, 30);
}
public static double futureInvestmentValue(double investmentAmmnt, double mri, int years)
{
NumberFormat df = DecimalFormat.getCurrencyInstance(Locale.US);
System.out.println("The amount invested: " + (df.format(investmentAmmnt)));
System.out.println("Annual interest rate: " + mri);
System.out.println("Years \t \t Future Value");
for (int i = 1; i <= years * 12; i++){
investmentAmmnt = investmentAmmnt * Math.pow(1 + (mri / 12),(years * 12));
if (i % 12 == 0){
System.out.println(i / 12 + "\t\t" + (df.format(investmentAmmnt)));
}
}
return investmentAmmnt;
}
}
The problem is that the formula futureValue = investmentAmmount * (1 + monthlyInterestRate)^numberOfYears*12 calculates the value of the investment for any amount of years in the future. The problem is that you for loop is calculating more than it needs to. That formula only needs to be done once. Your function futureInvestmentValue should not have a for loop.
Here's how it works:
public static double futureInvestmentValue(final double investmentAmmnt, double mri, int years)
{
NumberFormat df = DecimalFormat.getCurrencyInstance(Locale.US);
double amount = investmentAmmnt;
System.out.println("The amount invested: " + (df.format(investmentAmmnt)));
System.out.println("Annual interest rate: " + mri);
System.out.println("Years \t \t Future Value");
for (int i = 1; i <= years ; i++){
amount = investmentAmmnt * Math.pow(1 + (mri /100),(i ));
System.out.println(i + "\t\t" + (df.format(amount)));
}
return amount;
}
The problems are many with your code...
Your Increasing the amount with Math.pow() in a loop - that's why it goes wild.
Your loop iterates over years * 12 (months?)
Your doing wild *12 and /12 calculations you don't need.
--> output
Years Future Value
1 $1,030.00
2 $1,060.90
3 $1,092.73
4 $1,125.51
5 $1,159.27
6 $1,194.05
7 $1,229.87
8 $1,266.77
9 $1,304.77
10 $1,343.92
11 $1,384.23
12 $1,425.76
13 $1,468.53
14 $1,512.59
15 $1,557.97
16 $1,604.71
17 $1,652.85
18 $1,702.43
19 $1,753.51
20 $1,806.11
21 $1,860.29
22 $1,916.10
23 $1,973.59
24 $2,032.79
25 $2,093.78
26 $2,156.59
27 $2,221.29
28 $2,287.93
29 $2,356.57
30 $2,427.26
Related
My problem is: Suppose that one credit hour for a course is $100 at a school and that rate increases 4.3% every year. In how many years will the course’s credit hour costs tripled?
The rewrote this simple code many times, but just can't seem to get it.
I think i'm going about this the wrong way..
import java.util.Scanner;
public class MorenoJonathonCreditHourCostCalculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double cost = 100;
int years=0;
double sum=200;
double total;
while (cost >= sum) {
total = cost + 4.03;
++years;
}
System.out.println("The tuition will double in " + years + " years");
}
}
A rate increase of 4.3% means that in every step, the value is 4.3% bigger than the previous value. This can be described by the following formula:
V_n+1 = V_n + (V_n * 4.3%)
V_n+1 = V_n + (V_n * 0.043)
V_n+1 = V_n * (1 + 0.043)
V_n+1 = V_n * 1.043
In Java this boils down to simply cost *= 1.043;
You first stated " In how many years will the course’s credit hour cost tripled", but in your program you actually check for when it has doubled.
I assume you want to calculate the triple cost, so your program should now look something like this:
public static void main(String[] args) {
double cost = 100;
double tripleCost = 3 * cost;
int years = 0;
while(cost < tripleCost) {
cost *= 1.043;
years++;
}
System.out.println("It took " + years + " years.");
}
Which gives the following output:
It took 27 years.
I am not sure why you are adding to cost since it is a multiplication function:
FV(future value) = PV(present value) (1+r)^n
300 = 100(1.043)^n where you are looking for 'n'
Set up a while loop that operates while the future value is under 300 and adds to 'n'.
In my code I am having the user type in 3 things, and for the third input I ask for the number of years. However in my for loop I can't use the variable that I ask the user to input. For example if the user were to input "3", my code would do 15 years (which is the max).
double yearInvest;
double interRate;
double numOfYears = 3;
double amountBeforeTotal;
double amountTotal;
double years;
System.out.println("Compound Interest \n");
System.out.println("This program will print out a title table that will "
+ " display the amount of a yearly investment over a period of "
+ " up to 15 years. \n");
Scanner input = new Scanner(System.in);
System.out.println("Enter the yearly investment:");
yearInvest = input.nextDouble();
System.out.println("Enter the interest rate (%):");
interRate = input.nextDouble();
System.out.println("Enter the number of years:");
numOfYears = input.nextDouble();
for (years = 1; 15 >= years; years++) {
System.out.format("%-4s %22s %12s %8s \n ", "Year", "Amount in Account",
"Interest", "Total");
amountTotal = (yearInvest * (interRate / 100)) + yearInvest;
System.out.format("%-4.1f", years);
System.out.format("%18.2f", yearInvest);
System.out.format("%14.2f", interRate);
System.out.format("%15.2f", amountTotal);
}
P.S. I am still working on the code and it is not fully done. And I would also like some advice if possible.
System.out.println("Enter the number of years:");
numOfYears = input.nextDouble();
for (years = 1; 15 >= years; years++)
Your code is getting a user inputted numOfyears which for example would be 3, for your case. Your loop is from (1..15) no matter what, since your loop's 2nd parameter is: 15 >= years.
What you are looking for is (1..numOfYears)
System.out.println("Enter the number of years:");
numOfYears = input.nextDouble();
for (years = 1; years <= numOfYears; years++)
//...more code
There are a few things that I notice about your code that might not be exactly what you want.
Firstly you are storing all of your variables as doubles which are mainly used for storing floating point (i.e. numbers with a decimal place). In place of double it might be better to use int.
Next your for loop is always going to loop 15 times with years 1 to 15. If you want this to be only numOfYears times you should have a loop that compares to numOfYears
for (years = 1; years <= numOfYears; years++) {
//TODO
}
Lastly something that is quite important for coding and something that it is easy to ignore if teaching yourself is style.
for (years = 1; 15>=years; years++ ) {
System.out.format("%-4s %22s %12s %8s \n ", "Year", "Amount in Account", "Interest", "Total");
amountTotal = (yearInvest * (interRate / 100)) + yearInvest;
System.out.format("%-4.1f", years);
System.out.format("%18.2f", yearInvest);
System.out.format("%14.2f", interRate);
System.out.format("%15.2f", amountTotal);
}
This indentation gives a much clearer view of what is in your for loop and helps debugging and readablilty
You can try this if you want to print only 15 years interest rates.
for (years = 1; numOfYears >= years; years++) {
System.out.format("%-4s %22s %12s %8s \n ", "Year", "Amount in Account",
"Interest", "Total");
amountTotal = (yearInvest * (interRate / 100)) + yearInvest;
System.out.format("%-4.1f", years);
System.out.format("%18.2f", yearInvest);
System.out.format("%14.2f", interRate);
System.out.format("%15.2f", amountTotal);
if(years == 15) {
break;
}
}
This will print the interest of 15 years if user enters any number greater than 15 or else will print interest rates of all years if user enters number < 15.
I am showing the declining balance of a loan per year and the interest paid per year. The first and second year are always messed up, causing the rest of the years to not be correct. Also, how do I print a column with designated space for each entry, besides using spaces to separate them like I did?
My code:
int year;
periods = loanDurationYears*12;
double annualBalance = 0;
double annualInterest = 0;
int month = loanDurationYears-(loanDurationYears-1);
balance = loanAmount;
double interestForMonth = balance*((interestRate*.01)/12);
double principalForMonth = monthlyPayment - interestForMonth;
balance = balance - principalForMonth;
System.out.println("Annual balances");
System.out.printf("%s %s %s \n","Year","Interest","Balance");
for(int j=0;j<periods;j++)
{
month++;
year = month/12;
interestForMonth = balance*((interestRate*.01)/12);
principalForMonth = monthlyPayment - interestForMonth;
balance = balance - principalForMonth;
annualBalance = annualBalance + balance;
annualInterest = annualInterest + interestForMonth;
if(month%12 == 0)
{
System.out.printf("%d %.2f %.2f \n",year,annualInterest,annualBalance);
annualBalance = 0;
annualInterest = 0;
}
}
My output:
Year Interest Balance
1 4852.43 859718.74
2 5080.12 899718.26
3 4842.34 857208.50
4 4588.01 811738.89
5 4315.96 763103.31
6 4024.98 711081.35
7 3713.73 655437.20
8 3380.81 595918.66
9 3024.71 532255.97
10 2643.82 464160.58
11 2236.40 391323.84
12 1800.62 313415.64
13 1334.49 230082.85
14 835.91 140947.76
15 302.62 45606.39
How the output should look: (besides the columns not being aligned)
Year Interest Loan Balance
1 5965.23 86408.21
2 5715.14 82566.33
3 5447.64 78456.94
4 5161.51 74061.43
5 4855.46 69359.87
6 4528.10 64330.94
7 4177.95 58951.87
8 3803.41 53198.26
9 3402.80 47044.03
10 2974.29 40461.31
11 2515.95 33420.24
12 2025.70 25888.91
13 1501.31 17833.19
14 940.40 9216.58
15 340.45 -0.00
You are getting an incorrect starting amount because you adjust the balance before the for-loop. It looks like your for-loop expects to start with the full balance, but it's already been reduced. You should also either move the increment of month to the end of the loop, or start it at zero instead of 1.
This line will always initialize month to 1. Why bother with the math?
int month = loanDurationYears-(loanDurationYears-1);
I haven't tested this or anything but it should work. I'm sure it's not the best fix but something simple like this should work fine.
It simply checks the size of the variable and then uses different print statements depending on the size of it. Also as the year throws off alignment I've put some code that should fix that
if(month%12 == 0)
{
// Set the amount of decimals for all interest rates
DecimalFormat df = new DecimalFormat("#.##");
df.format(annualInterest);
// Get the length of annualInterest
int n = math.floor(annualInterest);
int length = (int)(Math.log10(n)+1);
if (length = 3)
{
// Have 1 less space than normal on the print statement
// Maybe also do a check on the year also as that throws it out when it goes past 10
if (year > 10)
System.out.printf("%d %.2f %.2f \n",year,annualInterest,annualBalance);
else
System.out.printf("%d %.2f %.2f \n",year,annualInterest,annualBalance);
}
if (length = 2)
{
// Have 2 less spaces than normal
}
annualBalance = 0;
annualInterest = 0;
}
I am new to Java and I'm trying to figure out how to dynamically calculate the change to the nearest 10 dollars. For instance, the user inputs a value (34.36), my code then calculates tip, tax, and total amount for the bill (total 44.24). Without user input, I need to calculate the change from $50.00. I've tried to round up to 50.00 from 44.24 with no luck, obviously I am doing something wrong. I've tried Math.round and tried to find the remainder using %. Any help on how to get the total change due to the nearest 10 dollar value would be great. Thank you in advance, below is my code:
Full dis-closer, this is a homework project.
import java.util.Scanner;
import java.text.NumberFormat;
import java.lang.Math.*;
public class test1
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
//Get input from user
System.out.println("Enter Bill Value: ");
double x = sc.nextDouble();
//Calculate the total bill
double salesTax = .0875;
double tipPercent = .2;
double taxTotal = (x * salesTax);
double tipTotal = (x * tipPercent);
double totalWithTax = (x + taxTotal);
double totalWithTaxAndTip = (x + taxTotal + tipTotal);
//TODO: Test Case 34.36...returns amount due to lower 10 number
//This is where I am getting stuck
double totalChange = (totalWithTaxAndTip % 10);
//Format and display the results
NumberFormat currency = NumberFormat.getCurrencyInstance();
NumberFormat percent = NumberFormat.getPercentInstance();
//Build Message / screen output
String message =
"Bill Value: " + currency.format(x) + "\n" +
"Tax Total: " + currency.format(taxTotal) + "\n" +
"Total with Tax: " + currency.format(totalWithTax) + "\n" +
"20 Percent Tip: " + currency.format(tipTotal) + "\n" +
"Total with Tax and 20 Percent Tip: " + currency.format(totalWithTaxAndTip) + "\n" +
"Total Change: " + currency.format(totalChange) + "\n";
System.out.println(message);
}
}
you make
double totalChange = round((totalWithTaxAndTip / 10)) * 10;
Math.round rounds a number to the nearest whole number, so as others have shown, you need to divide by 10, then multiply by 10 after rounding:
double totalChange = tenderedAmount - totalWithTaxAndTip;
double totalChangeRounded = 10 * Math.round(totalChange / 10);
Math.ceil(double) will round up a number. So what you need is something like that:
double totalChange = (int) Math.ceil(totalWithTaxAndTip / 10) * 10;
For totalWithTaxAndTip = 44.24, totalChange = 50.00
For totalWithTaxAndTip = 40.00, totalChange = 40.00
Everyone, thank you very much for helping me. I tested out everyone's solution. This is my final working code.....
double totalAmountPaid = totalWithTaxAndTip - (totalWithTaxAndTip % 10) + 10;
I tested it out using many different values and it seems to be working the way I want it to.
Again, I appreciate everyone for taking the time to help me out.
I'm working on a program that will calculate the basic interest accrued on a certificate of deposit. The program asks for the amount of money invested and the term (up to five years). Depending on how many years their term is, is what determines how much interest is earned. I use an if/else statement to determine the rate of interest. I then use a loop to print out how much money is in the account at the end of each year. My problem is that when I run the program, the money is not counting.
Here is the entire code.
import java.util.Scanner;
public class CDCalc
{
public static void main(String args[])
{
int Count = 0;
double Rate = 0;
double Total = 0;
Scanner userInput = new Scanner(System.in);
System.out.println("How much money do you want to invest?");
int Invest = userInput.nextInt();
System.out.println("How many years will your term be?");
int Term = userInput.nextInt();
System.out.println("Investing: " + Invest);
System.out.println(" Term: " + Term);
if (Term <= 1)
{
Rate = .3;
}
else if (Term <= 2)
{
Rate = .45;
}
else if (Term <= 3)
{
Rate = .95;
}
else if (Term <= 4)
{
Rate = 1.5;
}
else if (Term <= 5)
{
Rate = 1.8;
}
int count = 1;
while(count <= 5)
{
Total = Invest + (Invest * (Rate) / (100.0));
System.out.println("Value after year " + count + ": " + Total);
count++;
}
}
}
and here is the result I get with a 10 dollar investment, just to keep it simple, and a 5 year investment.
How much money do you want to invest?
10
How many years will your term be?
5
Investing: 10
Term: 5
Value after year 1: 10.18
Value after year 2: 10.18
Value after year 3: 10.18
Value after year 4: 10.18
Value after year 5: 10.18
My main problem is I dont know how to make it continually add the intrest onto the total. I'm not sure if I need to use a different loop or what. Any help would be appreciated.
Total = Invest + (Invest * (Rate) / (100.0));
You are not changing the value of Invest for each year, so it is not compounding. It is like you are getting .18$ of interest each year, retired from the account.
Change Total for Invest.
You need to add the investment interest to your total:
Total = Invest;
int count = 1;
while(count <= 5)
{
Total = Total + (Invest * (Rate) / (100.0));
System.out.println("Value after year " + count + ": " + Total);
count++;
}