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
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";
If the cases of your switch will always be consecutive (eg "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";
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.