简体   繁体   中英

How can I get my program to run the future values correctly?

Okay here is my code that I'm trying to create from a practice code from a text book. The question asked me to create a java console program that prompts the user to enter an investment amount and the interest rate. Furthermore, the program should use these inputs to calculate and list the future values (I'm doing it up to 5 periods).So for example, if I use an input such as 500 for Amount and 1 for interest rate the numbers that the program should display (from periods 1-5) are: 505.00, 510.05, 515.15, 520.30, 525.51. Any tips or help would be appreciated thank you! ^-^

import java.util.Scanner;

public class FutureValues {
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    String inputString;
    char letter = 'c';

    // Prompt the user to enter investment amount
    while(letter == 'c') {
      System.out.print("Enter your investment amount: ");
      int InvestmentAmount = input.nextInt();

    // Prompt the user to enter interest rate
      System.out.print("Enter the interest rate (%): ");
      int InterestRate = input.nextInt();  
      System.out.println("    "); 

    // Display the header
      System.out.println("The future values are: ");
      System.out.println("    ");

    // Display "Period" title and "rate" title
      System.out.println("Period        " + InterestRate + "% ");
      System.out.println("\n------     ------");

    // Display table body 

      for (int h = 1; h <= 5; h++) {
         System.out.print(h);
         System.out.printf("          %4.2f",  (double) (InterestRate) + 1 * InvestmentAmount);
         System.out.println("      ");

      }

      System.out.println("     ");
      System.out.print("Enter c to continue or any other character to quit: ");
      String character = input.nextLine();
      inputString = input.nextLine();
      letter = inputString.charAt(0);
    }
  }
}

I would suggest changing your InvestmentAmount and InterestRate as double instead of int (will save you from casting and creating an extra variable)

Then, your for loop needs to not only "print" your InvestmentAmount, but also update it, based on your interest.

  for (int h = 1; h <= 5; h++) {
    InvestmentAmount *= 1 + InterestRate / 100;
    System.out.print(h);
    System.out.printf("          %4.2f",  InvestmentAmount);
    System.out.println("      ");
  }

The Interest Rate is divide per 100 to give you a percentage (otherwise, 1 = 100%, 2 = 200%, etc...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM