Search code examples
javaarraysfor-loopexponential

exponential growth in java, return type array of doubles


Im working on a CS assignment and Im having a little trouble understanding how to output an array of doubles that represent the amt of money in a bank account at increments of time given a user specified growth rate. I have a main method that asks the user for initialAmount of $, a growthRate and the number of time intervals (denoted iA, gR and nP for inital Amount, growth Rate and number of Periods). this method then calls another method which is of return type double[]. My issue is with the code inside my for-loop, it compiles fine but outputs gibberish. heres the code:

import java.util.Scanner;

public class Benford {
    public static double[] generateBenfordNumbers (double iA, double gR, int nP) {  
        double[] bankStatement = new double[nP];

        for (int i = 0; i<nP; i++) { 
            bankStatement[i] = (iA*(Math.pow((1+(gR)), (i++))));
        }

        return bankStatement;
    }

    public static void main (String[] args) {
        Scanner scan = new Scanner(System.in); 
        double iA;
        double gR;
        int nP;

        System.out.print("What is the initial amount of money that you are starting with? : ");
        iA = scan.nextDouble();
        System.out.println();

        System.out.print("What is the amount of growth per time period? : ");
        gR = scan.nextDouble();
        System.out.println();

        System.out.print("How many time periods would you like to use? : ");
        nP = scan.nextInt();
        System.out.println();

        generateBenfordNumbers(iA, gR, nP);
        System.out.print(generateBenfordNumbers(iA, gR, nP));
    }
}

Solution

  • In the line

    bankStatement[i] = (iA*(Math.pow((1+(gR)), (i++))));
    

    i++ increments i a second time. You probably want:

    bankStatement[i] = (iA*(Math.pow((1+(gR)), i + 1)));
    

    or, if we clean it up,

    bankStatement[i] = iA * Math.pow(1 + gR, i + 1);
    

    i + 1 returns a value 1 greater than that of i, but does not actually increment the variable itself.


    Also, do you really have to use Math.pow each time? Can't you just manually set the first element of your array to iA and subsequently use bankStatement[i-1] to compute bankStatement[i]? Doing something like this will probably improve your program.