简体   繁体   中英

Arraylist - String/Double

I am taking a basic objects first with java class, i don't know much yet and need a little help .. I need to assign these values to an arraylist but also need to allow the user to choose a health option based on a string that will then output the value related to the option..

double [] healthBenDesig = new double [5];
double [] healthBenDesig = {0.00, 311.87, 592.56, 717.30, 882.60};

Strings I want to assign are:

none = 0.00
employeeOnly = 311.87
spouse = 592.56
children = 717.30
kids = 882.60 

Ultimately, I want the user to input for example "none" and the output will relate none to the value held in the arraylist [0] slot and return that value. Is this possible? Or is there an easier way I am overlooking?

if anyone could help me out I would really appreciate it :) Thanks

Yes. This is possible with HashMap .

HashMap<String,Double> healthMap = new HashMap<String,Double>();
healthMap.put("none",0.00);
healthMap.put("employeeOnly",311.87);
healthMap.put("spouse",592.56);
healthMap.put("children",717.30);
healthMap.put("kids",882.60);

Now, when user enters none then use get() method on healthMap to get the value.

For safety check that key exists in map using containsKey() method.

if(healthMap.containsKey("none")) {
   Double healthVal = healthMap.get("none"); //it will return Double value
} else {
  //show you have entered wrong input
}

See also

Best solution is Map<String, Double> .

Map<String,Double> map=new HashMap<>();
map.put("none",0.0);

Now when you want the value for "none" you can use get() method

map.get("none") // will return 0.0

Here's something for you to get started with since it's the assignment:

  1. Create a Map<String, Double> that holds the number and string as key/value pair.
  2. Store the above values into the map
  3. When a user enters the input, capture it using Scanner
  4. Do something like this.

     if(map.containsKey(input)) { value = map.get(input); } 

Use Map Inteface

Map<String, Double> healthBenDesig =new HashMap<String, Double>();
healthBenDesig.put("none", 0.00);
healthBenDesig.put("employeeOnly", 311.87);
healthBenDesig.put("spouse", 592.56);
healthBenDesig.put("children", 717.30);
healthBenDesig.put("kids", 882.60);

System.out.println(healthBenDesig);

OutPut

{
none = 0.0, 
spouse = 592.56, 
children = 717.3, 
kids = 882.6, 
employeeOnly = 311.87
}

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