在Java中从数组中选择随机字符串

时间:2015-02-13 11:19:54

标签: java android xml string indexoutofboundsexception

使用放在数组中的十个随机数,我想从另一个数组中选择十个随机字符串,但我得到ArrayIndexOutOfBoundsException

int[] RandomArray = new int[10]; // this is an array of random numbers between 0 and 21

String[] StringArray = new String[22]; //This array has 22 diffrent sentences and gets them from the string.xml

String[] ResultStringArray = new String[10]; //This array shall have now the 10 randomly picked sentences 

for (int i = 0; i < ResultStringArray.length; i++) {
    ResultStringArray[i] = StringArray[ResultArray[i]];
}

提供的代码有什么问题?

1 个答案:

答案 0 :(得分:2)

请尝试使用此代码:

int N=10;
int[] randomArray = new int[N]; // this is an array of random numbers between 0 and 21

String[] stringArray = new String[22]; //This array has 22 diffrent sentences and gets them from the string.xml

String[] resultStringArray = new String[N]; //This array shall have now the 10 randomly picked sentences 

for (int i = 0; i < resultStringArray.length; i++) {
    // Pick the stringArray index from randomArray and not from resultArray
    resultStringArray[i] = stringArray[randomArray[i]];
}