The idea behind this small program is to tell you how many
subscribers you would have after a given number of days if you assume compound
interest rate growth of 1% every day. Here’s the original code provided by the
video that uses a for loop.
class apples{
public static void main(String args[]){
double amount;
double principal = 10000;
double rate = .01;
for(int day=1; day<=20; day++){
amount = principal*Math.pow(1 + rate, day);
System.out.println(day + " " + amount);
}
}
}
Based on the compound interest formula of Amount = Principal*(1+rate)^time - this tells
you how much your subscribership grows over 20 days. By now I’m sort of getting
the hang of making these modular and generic though, so I want to see if I can
make it so you input an initial amount, an interest rate, and run it for any
number of days you want.
First thing to do is import the Scanner and make it so the program can receive input
import java.util.Scanner;
class apples{
public static void main(String args[]){
Scanner
input = new
Scanner(System.in);
Next we need to modify it so the principal and rate can
be entered, and make an empty integer variable for time to indicate the number of days you want it to calculate - while
we’re at it we may as well make the code more expressive to the user.
System.out.println("Interest rate
calculator");
System.out.println("Enter the principal
balance:");
double rate = input.nextDouble();
System.out.println("Enter the
number of days you want to run the calculator for: ");
int time = input.nextInt();
double amount;
Now to modify the for
loop to accept the time variable,
and to display the principal amount for the 0th day.
System.out.println(0 + " " + principal);
for(int day=1; day<=time; day++){
amount = principal*Math.pow(1 + rate, day);
}
And it works. It asks me for the principal balance, then the interest rate, then the number of days I want it to run, then it spits out the information in a neat little faux formatted table.
I wondered what would happen if you put 0 for
the time variable and was pleasantly
surprised to find that the program just sat there without doing anything. I was
half expecting an error, but dug a little deeper. Setting the code to start at
day 5 and the time to 2, and the calculator provides no information. Even
better, when I try to modify the code to do this:
for(int day=5; day<=day+time; day++){
amount = principal*Math.pow(1 + rate, day);
System.out.println(day + " " + amount);
}
With the same input
of 2 days for time, the for loop
runs forever and outputs “infinity” as the new amount, up to more than 100k
times in a few seconds. So the expected integer input for day must be higher than whatever the initial integer is hard coded
in as. At this point I’m not sure if it’s a limitation of the for loop or something else – either way
it’s a good lesson to start at 1 when setting up loops that incrementally
increase.
No comments:
Post a Comment