1

I was just simplifying my code and I ran into a small problem which I can't solve. So I have an activity which has a getter like so:

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";
    }

so instead of having numerous number of cases, I would rather simplify the code by something like this

public String getExerciseValue(String variableName ,int codeOrValue,int type){
        return variableName[codeOrValue][type];
    }

I ask for an example of working code work this case coz I have no idea how to figure this out. Thanks for any suggestions :)

Kristian
  • 165
  • 2
  • 16
  • 1
    Does this answer your question? [To use a string value as a variable name](https://stackoverflow.com/questions/20974558/to-use-a-string-value-as-a-variable-name) – micpap25 Nov 29 '20 at 07:05
  • @micpap25 not really since there was a single variable and I have an array, could you please gimme an example to my case? – Kristian Nov 29 '20 at 07:14

2 Answers2

0

Suggest you to use HashMap, and put each array as a value with your preferred name in it. Something like it:

Map<String, String[][]> examples = new HashMap<>();
examples.put("Example001", Example001);

You can then easily retrieve your element with its names and indexes as you needed.

examples.get("Example001")[codeOrValue][type]
khesam109
  • 510
  • 9
  • 16
0

This is not possible in Java. However, it is also not necessary.

Whenever you have series of numbered variable names, that's actually just a very cumbersome way of implementing an array:

private String[][][] examples = {
    {
        { "String1", "String2" }, 
        { "Light", "Normal", "Heavy" }
    }
};

public String getExerciseValue(int exampleNumber, int codeOrValue, int type) {
    return examples[exampleNumber - 1][codeOrValue][type];
}
Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653