Question: Write a program that reads in investment amount, annual interest rate, and number of years, and displays the future investment value using the following formula:
futureInvestmentValue = investmentAmount * (1 + monthlyInterestRate)^(numberOfYears * 12)
Warning!
Please import selected Java packages or use import java.util.*;. Do not copy my code as per copyright and plagiarism regulations. This Java code is provided as it is for demonstration purposes.Solution: Note the two possible methods of printing the output.
1) Display result by division method: In Java, if you divide a value with a decimal place, you can obtain an output with a decimal value. This can be used in place of a printf() function.
2) Display result using printf method: The printf() function allow you to format output. It should in the following order: %[flags][width][.precision]conversion-character. You can learn more about Java printf() on Oracle Java docs.
public class futureInvestment { public static void main(String[] args) { Scanner input = new Scanner(System.in); // Prompt the user to enter the investment amount, // annual interest rate and number of years. System.out.print("Enter investment amount: "); double amount = input.nextDouble(); System.out.print("Enter annual interest rate in percentage: "); double monthlyInterestRate = input.nextDouble(); monthlyInterestRate /= 1200; System.out.print("Enter number of years: "); int years = input.nextInt(); // Calculate future investment value double futureInvestmentValue = amount * Math.pow(1 + monthlyInterestRate, years * 12); // 1) Display result by division method System.out.println("Future value is $" + (int)(futureInvestmentValue * 100) / 100.0); // 2) Display result using printf method System.out.printf("Future value is $%.2f", futureInvestmentValue); } }
I would recommend that you use printf() method and get familiar with the format specifiers.
Output:
For example, if you enter amount 1000, annual interest rate 3.25%, and number of years 1, the future investment value is 1032.98
Enter investment amount: 1000.56
Enter annual interest rate in percentage: 4.25
Enter number of years: 1
Future value is $1043.92