如何显示花了多少个月?

时间:2015-03-02 16:38:02

标签: java string loops

继承我的代码:

import java.util.*;

public class LoanCalculator {

  static Scanner console = new Scanner(System.in);

  public static void main(String[] args) {

    //Declare variables
    double loanAmount;
    double interestRate;
    double monthlyPayment;
    double interest = 0;
    double principal = 0;
    int months;

    System.out.print("Enter the amount of your loan: ");
    loanAmount = console.nextDouble();
    System.out.println();

    System.out.print("Enter the interest rate per year: ");
    interestRate = console.nextDouble();
    System.out.println();

    System.out.print("Enter your monthly payment amount: ");
    monthlyPayment = console.nextDouble();
    System.out.println();

    interestRate = (interestRate / 12) /100;

    for (months = 1; months <= loanAmount; months++)
    {
        interest = (loanAmount * interestRate);
        principal = monthlyPayment - interest;
        loanAmount = loanAmount - principal;
        System.out.println(months);
    }
  }
}

我希望该计划能够输出贷款需要多少个月才能还清,但每个月都会列出。我怎样才能做到这一点?此外,如果每月付款少于第一个月的利息,那么贷款金额将增加,如果发生这种情况,我该如何警告用户?

1 个答案:

答案 0 :(得分:3)

要仅输出所花费的月数,请将System.out移出循环外部。警告用户在循环之前添加检查

if (monthlyPayment < loanAmount * interestRate) {
        System.out.println("your warning...");
}
for (months = 1; months <= loanAmount; months++) {
    interest = (loanAmount * interestRate);
    principal = monthlyPayment - interest;
    loanAmount = loanAmount - principal;
}
System.out.println("Number of months: " + months);