質問

I am working on a project for my introductory Java programming class where I have to create a program that calculates as user's future investment value. The user must be prompted for three things in the program: the amount of their investment, their annual interest rate, and the number of years they are investing in. With this information, the program should then be able to calculate the user's monthly interest rate and in turn their future investment value.

Let's start with my professor's future investment formula:

futureInvestmentValue = investmentAmount x (1 + monthlyInterestRate)^numberOfYears* 12

Next, here is my code so far:

public static void main(String[] args) {
    // Create scanner objects for investmentAmount, numberOfYears, and annualInterestRate
    Scanner investInput = new Scanner(System.in);
    Scanner rateInput = new Scanner(System.in);
    Scanner yearInput = new Scanner(System.in);

    // Declare variables
    int investmentAmount, numberOfYears;
    double annualInterestRate, rate, monthlyRate, futureInvestmentValue;

    // Create user inputs for investmentAmount, numberOfYears, and annualInterestRate
    System.out.print("Please enter your investment amount: ");
    investmentAmount = investInput.nextInt();

    System.out.print("Please enter your annual interest rate: ");
    annualInterestRate = rateInput.nextInt();

    System.out.print("Please enter the number of years for your investment: ");
    numberOfYears = yearInput.nextInt();

    // Variable assignments
    rate = annualInterestRate / 100;
    monthlyRate = rate / 12;
    futureInvestmentValue = investmentAmount * (1.0 + monthlyRate);

    //Output
    System.out.print("Your annual interest rate is " + rate +
        " and your monthly interest rate is " + monthlyRate);

    investInput.close();
    rateInput.close();
    yearInput.close();
}

I got as far as calculating the user's monthly interest rate based on their input, and also began translating my professor's formula into Java's language.
However, I can't figure out how to use the Math.pow method to translate the exponential part of my professor's equation.

役に立ちましたか?

解決

The formula could be translated to Java as:

double duration = numberOfYears * 12
double futureInvestmentValue = investmentAmount * Math.pow((1 + monthlyInterestRate), duration)

他のヒント

// if you want e^b:
double result = Math.exp(b);

// if you want a^b:
double result = Math.pow(a, b);

And don't forget to:

import java.lang.Math;

This is how to use Math.pow():

Math.pow ( x,y ); // x^y

where x = (1 + monthlyInterestRate) and y = numberOfYears* 12

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top