2014-10-01 108 views
-3

我必須在Java中創建一個程序,該程序使用一種方法來計算未來投資價值,同時用戶輸入投資金額和利率。它必須在表格中顯示並且有1-30年。錯誤:futureInvestmentValue無法解析爲變量

我有一個錯誤,我無法弄清楚如何解決。錯誤在//Titlemain之下,我有futureInvestmentValue。錯誤是告訴我,

futureInvestmentValue cannot be resolved to a variable

這裏是我的代碼:

import java.util.Scanner; 
public class futureInvestmentValue {  
    public static double futureInvestmentValue(double investmentAmount, 
     double monthlyInterestRate, int years){ 
     double futureInvestmentValue = 1; 

     for (years = 1; years <= 30; years++) { 
      monthlyInterestRate = years/1200; 
      futureInvestmentValue = 
       investmentAmount * Math.pow((1+monthlyInterestRate), years*12); 
     } 
     return futureInvestmentValue; 
    }   

    public static void main(String[] args) { 
     // TODO Auto-generated method stub 

     //Get investment amount and yearly interest rate from user 
     Scanner input = new Scanner (System.in); 
     System.out.print("Enter investment amount, for example 100:" + 
      "Enter yearly interest rate, for example 5.25:\n"); 
     double investmentAmount = input.nextDouble(); 
     double annualInterestRate = input.nextDouble(); 

     //Title 
     System.out.print("Years\t" + "\t Future Value"); 

     for (int years = 1; years <= 30; years++) { 
      System.out.print(years); 
      System.out.printf("%4d", futureInvestmentValue); 

     } 
     System.out.println();    
    }  
} 
+1

您在'futureInvestmentValue()'中聲明瞭該變量,因此您只能在該方法中訪問該變量。如果你想在'main()'中訪問,你需要聲明它是一個靜態的類變量。另一個選擇是在最後使用'()'在打印語句中調用該方法。 – csmckelvey 2014-10-01 22:01:46

+0

是的,因爲它不是一個變量,但你可以這樣使用它。 – njzk2 2014-10-01 22:02:00

回答

5

在main方法,你引用的變量,而不是函數的名稱...

System.out.printf("%4d", futureInvestmentValue); 

以上應該是:

順便說一句,這就是你給變量和函數賦予相同的名字。不要這樣做。

+1

當Visual Basic是您學習的第一種編程語言時,會發生這種情況。 – 2014-10-01 23:54:06