/* Craig Persiko - FunInterest.java
Sample Program using loops and a function for CS 111A
Uses a function to compute the new balance of a
specified investment with 5% interest after a period
of 10 years. Then uses the same function to show the
new balance of the same initial investment at other
interest rates and time periods.
*/
import java.util.Scanner;
class FunInterest
{
public static void main(String args[])
{
Scanner keyIn = new Scanner(System.in);
double init_balance, new_balance;
System.out.print("Welcome to Investment World\nEnter amount to be invested: ");
init_balance = keyIn.nextDouble();
// Compile interest for 10 years at 5%
new_balance = accrue_interest(init_balance, 0.05, 10);
// Output the result
System.out.printf("After 10 years at 5%%, your balance will be: $%,.2f\n", new_balance);
// Compile interest for 10 years at 10%
new_balance = accrue_interest(init_balance, 0.10, 10);
// Output the result
System.out.printf("After 10 years at 10%%, your balance will be: $%,.2f\n",
new_balance);
// Output the result of compiling interest
// for 7 years at 10%
System.out.printf("After 7 years at 10%%, your balance will be: $%,.2f\n",
accrue_interest(init_balance, 0.10, 7));
}
/* ***** accrue_interest method *****
Returns the new balance when cur_balance is invested for
specified number of years at specified interest rate.
*/
static double accrue_interest(double cur_balance, double rate, int years)
{
int elapsed_years = 0;
while(elapsed_years < years) // For specified number of years...
{
cur_balance += cur_balance * rate; // Add interest to the balance
elapsed_years++; // Add 1 to elapsed_years
}
return cur_balance;
}
}
/* SAMPLE OUTPUT:
Welcome to Investment World
Enter amount to be invested: 100
After 10 years at 5%, your balance will be: $162.89
After 10 years at 10%, your balance will be: $259.37
After 7 years at 10%, your balance will be: $194.87
*/
syntax highlighted by Code2HTML, v. 0.9