Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

For Loops (Java) Write an application that calculates the amount of money earned

ID: 3676082 • Letter: F

Question

For Loops (Java)

Write an application that calculates the amount of money earned on an investment, based on an 8% annual return. Prompt the user to enter an investment amount (present value) and the number of years for the investment. Display an error message if the user enters 0 for either value; otherwise, display the total amount (balance) for each year of the investment. Save the file as Investment.java. Use the compound interest formula for each year. where PV is the present value, r is the rate (as a decimal) and n is the number of years (you will want to show for year 1 through the user entered value).

Explanation / Answer

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.math.BigDecimal;

import java.math.RoundingMode;

public class Investment {

  

private static final double RATE_OF_INTEREST = 8;

   public static void main(String[] args) throws Exception {

       System.out.println("Please enter Investment amount: ");

       double p = Double.valueOf(readFromKeyboard());

       System.out.println("Please enter Number of years of investment: ");

       int noOfYears = Integer.valueOf(readFromKeyboard());

       if (p == 0 || noOfYears == 0) {

           System.err.println("invalid value for amount or noOfYear!");

           System.exit(0);

       }

       double r = RATE_OF_INTEREST / 100;

       BigDecimal principal = new BigDecimal(p);

       for (int t = 1; t <= noOfYears; t++) {

           BigDecimal totalAmount = principal.multiply((BigDecimal.ONE.add(new BigDecimal(r))).pow(t));

           System.out.println(String.format("Amount accrued after %s year(s) is %s", t, totalAmount.setScale(2, RoundingMode.HALF_EVEN)));

       }

   }

  

   public static String readFromKeyboard() throws IOException{

       InputStreamReader r = new InputStreamReader(System.in);

       BufferedReader br = new BufferedReader(r);        

       String msg = br.readLine();

       return msg;

   }

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote