Java 使用字符串值作为另一个变量的名称
我只是简化了我的代码,我遇到了一个我无法解决的小问题。 所以我有一个活动,它有一个getter,如下所示:Java 使用字符串值作为另一个变量的名称,java,Java,我只是简化了我的代码,我遇到了一个我无法解决的小问题。 所以我有一个活动,它有一个getter,如下所示: private String[][] Example001 ={{"String1","String2"},{"Light","Normal","Heavy"}}; public String getExerciseValue(String variableName ,int codeOr
private String[][] Example001 ={{"String1","String2"},{"Light","Normal","Heavy"}};
public String getExerciseValue(String variableName ,int codeOrValue,int type){
switch (variableName){
case "Example001":
return Example001[codeOrValue][type];
case "Example999"
return Example999[codeOrValue][type];
}
return "default";
}
因此,我宁愿通过这样的方式简化代码,而不是大量的案例
public String getExerciseValue(String variableName ,int codeOrValue,int type){
return variableName[codeOrValue][type];
}
我要求提供一个在这种情况下工作的代码示例,因为我不知道如何解决这个问题。感谢您的建议:)建议您使用HashMap,并将每个数组作为一个值,其中包含您的首选名称。类似的:
Map<String, String[][]> examples = new HashMap<>();
examples.put("Example001", Example001);
建议您使用HashMap,并将每个数组作为一个值,其中包含您的首选名称。类似的:
Map<String, String[][]> examples = new HashMap<>();
examples.put("Example001", Example001);
这在Java中是不可能的。然而,这也是没有必要的 当您有一系列编号的变量名时,这实际上只是实现数组的一种非常麻烦的方法:
private String[]示例={
{
{“String1”、“String2”},
{“轻”、“正常”、“重”}
}
};
公共字符串getExerciseValue(int-exampleNumber、int-codeOrValue、int-type){
返回示例[exampleNumber-1][codeOrValue][type];
}
这在Java中是不可能的。然而,这也是没有必要的
当您有一系列编号的变量名时,这实际上只是实现数组的一种非常麻烦的方法:
private String[]示例={
{
{“String1”、“String2”},
{“轻”、“正常”、“重”}
}
};
公共字符串getExerciseValue(int-exampleNumber、int-codeOrValue、int-type){
返回示例[exampleNumber-1][codeOrValue][type];
}
这是否回答了您的问题@micpap25不是真的,因为只有一个变量,我有一个数组,你能给我举个例子吗?这能回答你的问题吗@MICPA25不是真的,因为只有一个变量,我有一个数组,你能给我举个例子吗?