Reputation: 21
I am working on an android app project. I have an array which holds 55 words. Each word within this array has another array of words which it will use if it is selected. My problem is that I do not know how to access the second array using a variable.
Assuming I put the arrays within the java file and want to access the random array it might be something like:
for (int i = 0; i < variable_name.length; i++) {
arrayList.add(variable_name[i]);
}
this does not work.
If I put the array into an XML file I would try to access it something like this:
String[] some_array = getResources().getStringArray(R.array.variable_name);
this does not work.
While irrelevant to the discussion in Actionscript it would be done something like this:
for (var a:int = 0; a < this[variable_name+"Array"].length; a++){
tempWordList[a] = this[variable_name+"Array"][a];
}
One thing I should add is that the number of elements in the arrays accessed by a variable are not all the same. e.g. some may have four while another may have six or seven.
Thanks to the input below I was able to come up with a workable solution. I am new to programing so this my not be the most efficient solution but it does work.
String[] Words = { "zero", "one", "two" };
String[][] otherWords = { { "green", "blue" }, { "orange", "red" }, { "yellow", "purple" } };
for (int i = 0; i < Words.length; i++) {
if (Words[i] == targetWord) {
arrayLocation = i;
}
}
for (int i = 0; i < otherWords[arrayLocation].length; i++) {
String wordsToAdd = otherWords[arrayLocation][i];
newWordList.add(wordsToAdd);
}
If the string variable targetWord is equal to "one" the ArrayList newWordList will be equal to "orange" and "red"...
Thanks again
Upvotes: 2
Views: 445
Reputation: 2009
use like this..
mainArray.get(0).get(0).toString();
for geting value at index 0 from child array
and this for index 1 from child array
mainArray.get(0).get(1).toString();
Upvotes: 1
Reputation: 10479
Java doesn't allow non-integer indexes for arrays. You have two options. Manager two different arrays like:
String[] words = { "zero", "one", "two" };
String[][] otherWords = { { "green", "blue" }, { "orange", "red" }, { "yellow", "purple" } };
In a case like this, the index into the array 'words' is used to also index into the array 'otherWords' creating the association.
The other, simpler option is to use a Map<String, List<String>>
to store your values. In this case, you could simply call map.get("zero") and it would create a List containing the values "green" and "blue". You'd have to write code to load the map with your values so, in the end, you'd probably end up using a combination of the two options.
Upvotes: 2