2015-03-02 42 views
-1

繼承人我的代碼:如何顯示所花費的月數?

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

我希望程序輸出數月如何把貸款還清,但它每月上市。我怎樣才能做到這一點?此外,如果每月付款少於第一個月的利息,那麼貸款金額將增加,如果發生這種情況,我該如何警告用戶?

+0

它是關於數學而不是編程 – Burusothman 2015-03-02 16:44:51

回答

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); 
+0

謝謝nomis! – Marcus 2015-03-02 16:52:22

相關問題