我有10个String[]
类型的数组。从这10个数组我想随机选择1个字符串。
到目前为止,我已经创建了以下内容:
static final String[] puzzle1 = new String[] {"1" , "2" , "3" , "4" , "?" };
static final String[] puzzle2 = new String[] { "1" , "3" , "5" , "7" , "?"};
static final String[] puzzle3 = new String[] { "1" , "3" , "5" , "7" , "?"};
static final String[] puzzle4 = new String[] { "1" , "3" , "5" , "7" , "?"};
static final String[] puzzle5 = new String[] { "1" , "3" , "5" , "7" , "?"};
static final String[] select = new String[] { "puzzle1" , "puzzle2" , "puzzle3" ,
"puzzle4" , "puzzle5"};
Random rand = new Random();
int selectedString = rand.nextInt(select.length);
String selectedPuzzle = select[selectedString];
这允许我选择一个数组名称。但是我如何获得数组值呢?
答案 0 :(得分:2)
从这10个数组中我想随机选择1个字符串。
您只需选择一个随机数组,然后选择该数组中的随机元素。诀窍是存储一个或多个数组,而不是数组名称数组。
static final String[] puzzle1 = { "1", "2", "3", "4", "?" };
static final String[] puzzle2 = { "1", "3", "5", "7", "?" };
static final String[] puzzle3 = { "1", "3", "5", "7", "?" };
static final String[] puzzle4 = { "1", "3", "5", "7", "?" };
static final String[] puzzle5 = { "1", "3", "5", "7", "?" };
static final String[][] allPuzzles = { puzzle1, puzzle2, puzzle3, puzzle4,
puzzle5 };
public static String chooseRandomString() {
Random rand = new Random();
String[] selectedPuzzle = allPuzzles[rand.nextInt(allPuzzles.length)];
return selectedPuzzle[rand.nextInt(selectedPuzzle.length)];
}
答案 1 :(得分:0)
简单的答案是
String thirdElementOfPuzzle2 = select[2];
但基本上你的select
所指的是错误的
String [] select;
switch (selectedString ) {
case :0
select = puzzle1;
break;
case 1:
select = puzzle2;
//etc
目前
String selectedPuzzle = select[selectedString];
你得到的只是谜题的name
。除非您使用反射,否则无法动态地使用名称访问数组,因此您必须进行相等性测试,例如如果我选择数字0然后给我第一个谜题,如果我选择1给我第二个谜题然后你可以将选择的谜题分配给一个通用数组,然后可以在你的代码中引用。
答案 2 :(得分:0)
将Select数组更改为二维String[][]
将所有数组放在select[][]
从随机选择的数组中随机获取值
public static void main(String args[]){
final String[] puzzle1 = new String[] {"1" , "2" , "3" , "4" , "?" };
final String[] puzzle2 = new String[] { "1" , "3" , "5" , "7" , "?"};
final String[] puzzle3 = new String[] { "1" , "3" , "5" , "7" , "?"};
final String[] puzzle4 = new String[] { "1" , "3" , "5" , "7" , "?"};
final String[] puzzle5 = new String[] { "1" , "3" , "5" , "7" , "?"};
final String[][] select = new String[][] { puzzle1 , puzzle2 , puzzle3 , puzzle4 , puzzle5};
Random rand = new Random();
int selectedString = rand.nextInt(select.length);
String selectedPuzzle = select[selectedString][selectedString];
System.out.print(selectedPuzzle );
}