如何让我的程序正确运行未来的值?

时间:2016-03-30 01:30:24

标签: java

好的,这是我的代码,我试图从教科书的练习代码中创建。这个问题让我创建一个java控制台程序,提示用户输入投资金额和利率。此外,程序应该使用这些输入来计算和列出未来的值(我最多可以执行5个周期)。例如,如果我使用500作为金额和1作为利率的输入数字该程序应显示(从1-5期):505.00,510.05,515.15,520.30,525.51。任何提示或帮助将不胜感激,谢谢! ^ - ^

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);
    }
  }
}

1 个答案:

答案 0 :(得分:0)

我建议将InvestmentAmountInterestRate更改为double而不是int(将使您免于转换并创建额外的变量)

然后,您的for循环不仅需要“打印”您的InvestmentAmount,还需要根据您的兴趣对其进行更新。

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

利率是每百分差给你一个百分比(否则,1 = 100%,2 = 200%等......)