Welcome to the CSC Q&A, where you can get help (and share your knowledge) about computer science!

Practice MT2: Q10 (computeBalance)

+10 votes

What answer did you get for this one?

(Again, you can use the <> "add code" button to add better-formatted Java code to your Q&A answers.)

asked Jan 25, 2015 in (Winter 14) by Forrest Stonedahl (3,308 points)

1 Answer

+4 votes
public class InvestmentCalculator  {
	public static final double INTEREST = 0.055;

	public static void main(String[] args) {

	Scanner console = new Scanner(System.in);
	System.out.print("Monthy investment? ");
	double monthRate = console.nextDouble();
	System.out.print("Years to invest? ");
	int years = console.nextInt();
	double result = computeBalance(monthRate, years);
	System.out.println("Investing " + monthRate + " each month for " + years + ",");
	System.out.printf("your balance will be $ %.2f\n", result );
	public static double computeBalance(double deposit, int years) {
		double monthInterest = INTEREST / 12;
		double numberMonths = years * 12;
		return deposit * ((Math.pow((1 + monthInterest), numberMonths) - 1) / monthInterest);



answered Jan 26, 2015 by Alerik Vi (100 points)
In the last line before the last method, shouldn't there be a + symbol before the word result?
If I had used a print/println statement, then yes it would've been.

I used a printf (format) command instead because since result was declared as a double, it would've printed an irrational number. Using printf, I was able to get the result to just two decimal places as desired when dealing with currency.
I have not tested this answer, but you can try it out yourself in Eclipse... and see if it works!

(And Al's use of printf with %.2f was a fine choice here, to format the currency properly.)