我正在尝试从 3 个字符串数组中随机选择元素?
private static String[] one ={"dog, cat"};
private static String[] two ={"ate, ran"};
private static String[] three ={"away, some}"
Random words = new Random();
int index=words.nextInt(one.length+two.length+three.length);
System.out.println(one[index]);
最佳答案
该程序的问题在于,您获得了 0 到 6 之间的随机数,然后使用该随机数作为索引仅从第一个数组中获取值。这里有两个问题,
one[index] 在某些情况下会导致 arrayindexoutofboundsException,因为 1 的最大索引为 1,而索引也可以为 2、3、4 或 5。
此外,目标是从三个字符串数组中获取随机元素,而不仅仅是一个
我的建议是获取 1 到 3(含)之间的随机数来选择字符串数组之一,然后找到 0 到所选数组长度之间的随机数。并将其分配给所选数组的索引。
关于java - 我试图从 3 个字符串数组中随机选择元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34280589/