我正在学习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;
}
}
HomeValue class :显示房屋价值
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获取值?
谢谢。
答案 0 :(得分:2)
答案 1 :(得分: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);
}
现在,您只需使用费率即可完成计算。