[英]Arraylist - String/Double
我首先使用Java類來學習基本對象,但我還不了解很多,需要一點幫助..我需要將這些值分配給arraylist,但還需要允許用戶基於字符串選擇運行狀況選項然后將輸出與該選項相關的值。
double [] healthBenDesig = new double [5];
double [] healthBenDesig = {0.00, 311.87, 592.56, 717.30, 882.60};
我要分配的字符串是:
none = 0.00
employeeOnly = 311.87
spouse = 592.56
children = 717.30
kids = 882.60
最終,我希望用戶輸入例如“ none”,並且輸出將不與arraylist [0]插槽中保存的值相關,並返回該值。 這可能嗎? 還是有一種更容易忽略的方法?
如果有人可以幫助我,我將非常感激:)謝謝
是。 使用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);
現在,當用戶不輸入none
時,請在healthMap
上使用get()
方法獲取值。
為了安全起見,請使用containsKey()
方法檢查映射中是否存在密鑰。
if(healthMap.containsKey("none")) {
Double healthVal = healthMap.get("none"); //it will return Double value
} else {
//show you have entered wrong input
}
最好的解決方案是Map<String, Double>
。
Map<String,Double> map=new HashMap<>();
map.put("none",0.0);
現在,當您想要“ none”的值時,可以使用get()
方法
map.get("none") // will return 0.0
這是作業,因此您可以從這里開始:
Map<String, Double>
,將數字和字符串作為鍵/值對保存。 做這樣的事情。
if(map.containsKey(input)) { value = map.get(input); }
使用地圖界面
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);
輸出
{
none = 0.0,
spouse = 592.56,
children = 717.3,
kids = 882.6,
employeeOnly = 311.87
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.