我可以根据数组中的值来命名变量吗?

问题描述 投票:0回答:1

如果我有一个数组,我可以使用它里面的值来命名变量吗?

到目前为止我试过......

String Statement = "Please enter the ";
String[] Variables = {"Weight", "Length", "Height", "Width", 
"Zones"};


for (int x = 0; x <= 3; x++) {
        double Array.get(Variables, x) = UI.askDouble(Statement + Variables[x] + " (kg): ");
    }

没有运气。

java arrays
1个回答
1
投票

我不知道你是否希望你想要,但地图是一种数据结构,可能更适合你的想法:

Map<String, Double> vals = new HashMap<>();
vals.put("Weight", 100.5d);
vals.put("Length", 2.0d);
// now access those keys
System.out.println("Weight = " + vals.get("Weight");

或者,更好的是,您可以使用这些字段定义POJO,例如

public class Measurements {
    private double weight;
    private double length;
    private double height;
    private double width;
    private double zones;

    // constructor and getters/setters
}

然后,您可以使用此POJO作为包装器一次存储所有感兴趣的值。

© www.soinside.com 2019 - 2024. All rights reserved.