Reputation: 77
I am working on some code where I have this snippet
{
user = "B";
indice = 21;
switch (user) {
case "A":
A[indice - 1] = "X";
break;
case "B":
B[indice - 1] = "X";
break;
case "C":
C[indice - 1] = "X";
break;
}
}
I was wondering if there is a possible way to make this code more efficiently so I don't have to rewrite it X ammount of times there could also be more values then the ammount of switch's I have setup, any help would be much advice would be a great help
Upvotes: 2
Views: 99
Reputation: 129587
If the cases of your switch will always be consecutive (e.g. "A", "B", "C"
) and will always be single-character, you could do something along the lines of
String[][] master = {A, B, C};
...
master[user.charAt(0) - 'A'][indice - 1] = "X";
Upvotes: 2
Reputation: 727047
Create a Map<String,String[]>
, put the arrays A
, B
and C
in it, and then use this code:
Map<String,String[]> arrayByName = new HashMap<String,String[]>();
arrayByName.put("A", A);
arrayByName.put("B", B);
arrayByName.put("C", C);
...
arrayByName.get(user)[indice-1] = "X";
Upvotes: 4