In: Computer Science
Write a JAVA program that asks a user to specify the number of months, investment amount and compound interest rate in % (per annum)
• Your program should then print each month, starting balance, interest earned and ending balance
• Your program is not expected to handle more than 5 months
• The balance and ending balance should be printed rounded to 2 decimal places
• You should utilise String.format() to display each line of the output. This function can be used to evenly space the output and also print doubles to a certain precision
• Text written in red below indicates user input
WANTED OUTCOME
Enter number of months: 5
Enter amount: 10
Enter interest rate (%): 6
Month | Opening Balance | Interest | Closing Balance |
1 | 10.00 | 0.05 | 10.05 |
2 | 10.05 | 0.05 | 10.10 |
3 | 10.10 | 0.05 | 10.15 |
4 | 10.15 | 0.05 | 10.20 |
5 | 10.20 | 0.05 | 10.25 |
import java.util.Scanner;
public class MyClass {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of months: ");
int months = sc.nextInt();
System.out.print("Enter amount: ");
double amount = sc.nextDouble();
System.out.print("Enter interest rate (%): ");
double r = sc.nextDouble()/12;
double each = amount*r/100, now = amount;
System.out.println("Month Opening Balance Interest Closing
Balance");
for(int i=1; i<=months; i++)
{
System.out.print(String.format("%3d %14.2f %14.2f", i, now,
each));
now = now + each;
System.out.println(String.format("%12.2f", now));
}
}
}
// Hit the thumbs up if you are fine with the answer. Happy Learning!