1

The following is the code snippet:

int[] cdb1 = {2,1,1,5,5};
int[] cbd2 = {3,1,1,2,2,6,6};
int[] cbd3 = {3,2,2,3,3,7,7};
int[] cbd4 = {2,3,3,4,4};
int[] cbd5 = {4,4,4,5,5,6,6,7,7};
String this_cdb = "cdb"+Integer.toString(router_id);
int this_cbd_number = this_cdb[0];

I get the following error: array required, but String found int this_cbd_number = this_cdb[0];

here router_id can be 1 2 3 4 or 5. I know I declared this_cdb as String. But how do I reference it to the right array name?

2 Answers 2

3

Without reflection you can't do references to other variables/fields/classes from a String. You would need to encapsulate your arrays e.g. inside another array or a List. Example (assuming router is indexed from 1):

int[] cdb1 = {2,1,1,5,5};
int[] cbd2 = {3,1,1,2,2,6,6};
int[] cbd3 = {3,2,2,3,3,7,7};
int[] cbd4 = {2,3,3,4,4};
int[] cbd5 = {4,4,4,5,5,6,6,7,7};
int[][] cdb = {cdb1, cdb2, cdb3, cdb4, cdb5};
int this_cbd_number = cdb[router_id - 1][0];
Sign up to request clarification or add additional context in comments.

Comments

1

Try putting all of the arrays into some kind of a data structure, like a LinkedList:

LinkedList<int[]> arrayList = new LinkedList<>();
arrayList.add(cdb1);
arrayList.add(cdb2);
arrayList.add(cdb3);
arrayList.add(cdb4);
arrayList.add(cdb5);
int this_cbd_number = arrayList.get(router_id)[0];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.