2015-04-17 89 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! –