Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/368.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java-从双数组中获取变量名_Java_Arrays - Fatal编程技术网

Java-从双数组中获取变量名

Java-从双数组中获取变量名,java,arrays,Java,Arrays,我有一个double类型的Java数组,其中变量名用于存储值,如下所示: double [] countArray = {teaCount, hotMealCount, drinkWaterCount, phoneCallCount}; 我希望通过索引打印出变量的名称 e、 g.如果我请求countArray[0],它将返回teaCount而不是存储的double。使用这种方法不可能实现您想要的操作。一个解决方案是使用一个映射,在该映射中将名称存储为键,将计数存储为映射中的值 实际上,变量名是

我有一个double类型的Java数组,其中变量名用于存储值,如下所示:

double [] countArray = {teaCount, hotMealCount, drinkWaterCount, phoneCallCount};
我希望通过索引打印出变量的名称


e、 g.如果我请求countArray[0],它将返回teaCount而不是存储的double。

使用这种方法不可能实现您想要的操作。一个解决方案是使用一个映射,在该映射中将名称存储为键,将计数存储为映射中的值


实际上,变量名是暂时的,以后无法访问该名称。如果向数组中添加了某些内容,则不会按名称向数组中添加变量,而是按值位置添加变量

Yor正在存储字符串,而不是数组中的双值

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

System.out.PrintLCountArray[0]

这将打印teaCount


希望它能起作用。

你不能按照你想要的方式来做,但地图可以成为你的解决方案:

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

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

如果您想要这些名称,您需要存储这些名称

String[] countArray = {"teaCount", "hotMealCount", "drinkWaterCount", "phoneCallCount"};
虽然你很可能想要一张地图,比如


这会存储名称和它的值。

我认为映射更适合这个问题。使用映射,Java不会以这种方式工作。请注意:不能在容器中使用double,必须在装箱/取消装箱时使用double。图书馆是这样做的,这不是他所要求的。把问题再读一遍。他有一个存储双变量的数组,他想得到存储在数组特定索引中的变量名。
Map<String, Double> map = new LinkedHashMap<>();
map.put("teaCount", teaCount);
map.put("hotMealCount", hotMealCount);
map.put("drinkWaterCount", drinkWaterCount);
map.put("phoneCallCount", phoneCallCount);