简体   繁体   中英

Java HashMap - get value from HashMap, user input

I am learning HashMap and trying to write a mortgage program. I thought that I would use the following in my HashMap

30 Years 3.95 15 Years 3.25

Here is so far what I have written

Loan Class : Getting user input

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 : Showing home value

public class HomeValue {    
    public int hValue= 300000;
}

CaclPrice class : This is where calculation happens based on user input of the year

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 *???
        }
    }
}

My Question: I do no want to hard code the calculation (home value* 3.25%) is there a way to get value from the HashMap based on the user input?

Thank You.

Map offers a get method which take the key as parameter.

So you can simply do rate.get(year) .

Note that null will be returned if no value match the key.

Might I suggest restructuring the code a little bit. In your Loan class, I would recommend implementing a getRate() function instead of getYear() function.

Now, your Loan class might look something like this....

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);
  }
}

And you can refactor your CalcPrice to look something like this....

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);
}

Now, you can just use the rate to complete your calculation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM