In: Computer Science
Create a Java Program to calculate compound interest.
This can all be done in the main() method.
Example:
Number of years to invest:5
Amount to Invest:1000 Year 1 balance = 1050.00 Year 2 balance = 1102.50 Year 3 balance = 1157.63 Year 4 balance = 1215.51 Year 5 balance = 1276.28 Display the message "You have doubled your investment" and terminate the loop if/when you have more than doubled your initial investment.
Answer:
I have written the below Java program based on your requirements.
The below code has no-error and it is working perfectly.
I have also attached the Output Screenshot that I got by running the below program.
Just save the below Java file as Main.java and then Compile & run.
***********************************************************************************************************
Output:
*********************************************************************************************************************
Code:
Main.java
import java.io.*;
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner sc=new
Scanner(System.in);
double currentBalance,
newBalance;
final double
INTEREST_RATE=1.05;
int yearCount;
System.out.print("\nNumber of years
to invest:");
yearCount=sc.nextInt();
System.out.print("Amount to
Invest:");
currentBalance=sc.nextDouble();
newBalance=currentBalance;
System.out.println();
for(int
i=1;i<=yearCount;i++)
{
newBalance=newBalance*INTEREST_RATE;
if(newBalance>=currentBalance*2)
{
System.out.println("You have doubled your
investment");
break;
}
System.out.println("Year "+i+" balance = "+String.format("%.2f",
newBalance));
}
}
}