我正在尝试从二维数组中随机选择一个元素。我特别只列举了一个元素x1
public static void main(String[] args) {
Random rand = new Random();
String[][] couples = {{"x1","y1"},{"x2","y2"},{"x3","y3"},{"x4","y4"},{"x5","y5"}};
int rnd=rand.nextInt(couples.length);
System.out.println(couples[rnd]);
}
这是我到目前为止所获得的,但它打印出来了:[Ljava.lang.String; @ 4517d9a3
答案 0 :(得分:1)
private var saveJob: Job? = null
fun save() {
saveJob = someScope.launch {
saveJob?.join()
withContext(Dispatchers.IO) {
// suspending database operation
}
}
}
答案 1 :(得分:1)
这里,您只为第一个数组的元素指定随机数。由于第一个数组中的元素是另一个包含两个元素的数组,因此您必须指定另一个随机数以选择一个如下所示的数字,
public static void main(String[] args)
{
Random rand = new Random();
String[][] couples = { { "x1", "y1" }, { "x2", "y2" }, { "x3", "y3" }, { "x4", "y4" }, { "x5", "y5" } };
int rndOne = rand.nextInt(couples.length);
int rndTwo = rand.nextInt(couples[rndOne].length);
System.out.println(couples[rndOne][rndTwo]);
}
答案 2 :(得分:0)
System.out.println(couples[rnd])
给你
[Ljava.lang.String;@4517d9a3
这意味着您的对象是String []
记住couples
是一个字符串[] [];一个2D数组,因此给出一个索引会返回另一个String [],而不是单个String。
您需要从String []中选择另一个索引
类似
int rnd=rand.nextInt(couples.length);
int rnd2 = rand.nextInt(couples[rnd]);
System.out.println(couples[rnd][rnd2]);
另外,请查看https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#getName,以了解获得[Ljava.lang.String;@4517d9a3
的原因。