2016-04-14 118 views
-1

得到變量名我有一個類型的Java數組雙與用於存儲值那麼變量名:爪哇 - 從雙陣列

double [] countArray = {teaCount, hotMealCount, drinkWaterCount, phoneCallCount}; 

我希望通過它的索引打印變量出了名。

例如如果我請求countArray[0],它將返回teaCount而不是存儲的雙倍數。

+2

我認爲地圖對於這個問題更好。 –

+4

使用地圖,Java不能這樣工作 – MadProgrammer

回答

4

如果你想你需要存儲這些

String[] countArray = {"teaCount", "hotMealCount", "drinkWaterCount", "phoneCallCount"}; 

雖然最有可能是你的名字想要一個Map<String, Double>

Map<String, Double> map = new LinkedHashMap<>(); 
map.put("teaCount", teaCount); 
map.put("hotMealCount", hotMealCount); 
map.put("drinkWaterCount", drinkWaterCount); 
map.put("phoneCallCount", phoneCallCount); 

這兩個存儲名稱找到它的價值。

2

你想要做什麼是不可能的這種方法。一個解決方案將有一個Map<String, Double>您存儲的名稱作爲關鍵和計數作爲Map中的值。

實際上,變量名稱是暫時性的,您以後無法訪問該名稱。而且,如果向數組添加某些內容,則不會將該變量按名稱添加到數組中,而是將該值添加到數值位置。

0

Yor正在存儲字符串,而不是數組中的double值。

如果要打印索引值,只需使用:

的System.out.println(countArray [0]);

而且會打印teaCount。

希望它有效。

+0

這不是他要求的。再次閱讀問題。他有一個存儲雙變量的數組,他希望獲取存儲在其數組的特定索引中的變量的名稱。 – goncalopinto

3

你不能做到這一點,你所希望的方式,但Map coould您的解決方案:

Map<String, Double> count = new HashMap<String, Double>(); 
count.put("teaCount", 1.5); 
count.put("hotMealCount", 2.5); 
// etc 

count.get("teaCount"); // 1.5 
+0

只是一個說明:你不能在容器中使用double,你必須使用Double(所有的裝箱/拆箱)。圖書館,它是http://trove.starlight-systems.com/ – Exceptyon