2013-10-03 43 views
0

我想在最後寫一個do while while循環來編寫這個複利興趣程序,我無法弄清楚如何打印出最終的金額。Java中的複合興趣程序

這裏是我到目前爲止的代碼:

public static void main(String[] args) { 
    double amount; 
    double rate; 
    double year; 

    System.out.println("This program, with user input, computes interest.\n" + 
    "It allows for multiple computations.\n" + 
    "User will input initial cost, interest rate and number of years."); 

    Scanner keyboard = new Scanner(System.in); 

    System.out.println("What is the initial cost?"); 
    amount = keyboard.nextDouble(); 

    System.out.println("What is the interest rate?"); 
    rate = keyboard.nextDouble(); 
    rate = rate/100; 

    System.out.println("How many years?"); 
    year = keyboard.nextInt(); 


    for (int x = 1; x < year; x++){ 
     amount = amount * Math.pow(1.0 + rate, year); 
       } 
    System.out.println("For " + year + " years an initial " + amount + " cost compounded at a rate of " + rate + " will grow to " + amount); 


    String go = "n"; 
    do{ 
     System.out.println("Continue Y/N"); 
     go = keyboard.nextLine(); 
    }while (go.equals("Y") || go.equals("y")); 
} 

}

回答

1

麻煩的是,amount = amount * Math.pow(1.0 + rate, year);。您將用計算的金額覆蓋原始金額。您需要一個單獨的值來保持計算的值,同時仍保持原始值。

所以:

double finalAmount = amount * Math.pow(1.0 + rate, year); 
在輸出

然後:

System.out.println("For " + year + " years an initial " + amount + 
    " cost compounded at a rate of " + rate + " will grow to " + finalAmount); 

編輯:另外,您也可以節省一條線,一個變量,只是做了計算內聯,因爲這樣的:

System.out.println("For " + year + " years an initial " + amount + 
    " cost compounded at a rate of " + rate + " will grow to " + 
    (amount * Math.pow(1.0 + rate, year))); 
+0

做內聯計算固定一切!以另一種方式做它是給我「finalAmount的未知變量」的錯誤 –

+0

謝謝! :)你們真棒 –

+0

@MicahCalamosca哦,對不起。爲了做到這一點,使用'finalAmount',你需要聲明'finalAmount'變量,就像你聲明所有其他變量一樣。無論如何,我很高興你的工作。如果您使用我的解決方案,請接受它作爲答案。謝謝。 – nhgrif