2015-04-17 38 views
1

我正在學習HashMap並試圖編寫抵押貸款計劃。我以爲我會用我的HashMap以下Java HashMap - 從HashMap獲取值,用戶輸入

30年3.95 15年3.25

這是迄今爲止我已經寫

貸款類:獲取用戶輸入

import java.util.*; 

public class Loan { 

    private static HashMap<Integer,Double> rate = new HashMap<Integer,Double>(); 

    public int getYear() { 
     rate.put(15, 3.25); 
     rate.put(30, 3.95); 

     System.out.println("Enter year: 15/30"); 
     Scanner userInput = new Scanner(System.in); 

     int year = userInput.nextInt(); 

     if (rate.containsKey(year)) { 

     } 
     return year; 
    } 

} 

首頁值類別:顯示房屋價值

public class HomeValue {  
    public int hValue= 300000; 
} 

CaclPrice類:其中計算偏偏基礎上,今年的用戶輸入這是

public class CalcPrice { 

    Loan ln= new Loan(); 
    HomeValue hv= new HomeValue(); 

    public double getPrice() { 

     if (ln.getYear()==15) { 
      System.out.println("House price is " + hv.hvalue *??? 
     } 
    } 
} 

我的問題:我沒有想硬編碼的計算(房屋價值* 3.25%)有一種基於用戶輸入從HashMap獲取價值的方法?

謝謝。

回答

1

可能我建議稍微重構代碼。在您的貸款課程中,我會建議實施getRate()函數,而不是getYear()函數。現在

,您的貸款類可能是這個樣子....

public class Loan { 

    private static HashMap<Integer,Double> rate = new HashMap<Integer,Double>(); 

    Loan() 
    { 
    //I would recommend populating the rate HashMap 
    //in the constructor so it isn't populated 
    //every time you call getRate 
    rate.put(15, 3.25); 
    rate.put(30, 3.95); 
    } 

    public double getRate(int year) { 
    //Now you can just the desired rate 
    return rate.get(year); 
    } 
} 

而且可以重構CalcPrice看起來是這樣的....

public double getPrice(){ 

    //I would recommend asking the user for input here 
    //Or even better, ask for it earlier in the program 
    //and pass it in as a parameter to this function 

    //You can easily get the rate now that you have the year 
    double rate = ln.getRate(year); 
} 

現在,你可以使用該費率來完成您的計算。

+1

謝謝,好主意會嘗試那個。 –

2

Map提供了一個get方法,它以關鍵字爲參數。

所以你可以簡單地做rate.get(year)

請注意,如果沒有與密鑰匹配的值,將返回null

+1

好緊湊,完整的答案!文檔也有很好的鏈接! Upvote for you! –