【问题标题】:Choosing random strings from an array in Java从Java中的数组中选择随机字符串
【发布时间】:2015-02-13 11:19:53
【问题描述】:

使用放置在一个数组中的十个随机数,我想从另一个数组中选择十个随机字符串,但我得到了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]];
}

提供的代码有什么问题?

【问题讨论】:

  • ResultArray 的大小比 StringArray 大
  • 另外(更多的约定),你的变量应该以小写字母开头。规范是使用大写的类名。
  • 你没有显示ResultArray的声明。您似乎将ResultArrayRandomArray 混为一谈。
  • 你为什么不直接打乱数组(或者更好地使用ArrayList&lt;String&gt;而不是(它比String[]更灵活)和Colections.shuffle(...))并首先取N(10-在你的情况下) 元素?

标签: java android xml string indexoutofboundsexception


【解决方案1】:

试试这个代码:

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]];
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-04
    • 2020-02-04
    • 2014-03-10
    相关资源
    最近更新 更多