【问题标题】:Can I name a variable based on a value in an array?我可以根据数组中的值命名变量吗?
【发布时间】:2019-08-03 17:56:59
【问题描述】:

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

到目前为止,我已经尝试过......

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】:

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

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 作为包装器来一次存储所有感兴趣的值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 2021-08-20
    • 2011-07-01
    • 2019-05-25
    • 2021-08-23
    • 2019-01-11
    相关资源
    最近更新 更多