gpt4 book ai didi

java - java中的两个数组打乱顺序

转载 作者:行者123 更新时间:2023-11-30 04:00:46 25 4
gpt4 key购买 nike

抱歉,我是java初学者。我定义了两个数组。其中一种类型是字符串,另一种类型是整数。现在,我想对它们进行洗牌。假设 id = {12, 45, 78, 23} 且 name = {"math", "physical", "art", "computer"}。例如,在洗牌后,数组将变为 id = {78,45,23,12} 和 name = {"physical", "art", "math", "computer"}。我写了下面的代码,但不起作用。我该如何修复它?

public class RandomNumber {

public static void main(String[] args)
{
long[] numbers = new long[4];
Scanner input = new Scanner(System.in);
Random id = new Random(4);
String[] name = new String[4];

for (int i=0; i<=numbers.length; i++)
{
System.out.print("Enter the numbers: ");
numbers[i] = input.nextLong();
}
for (int i=0; i<=numbers.length; i++)
{
int randomPosition = id.nextInt(4);
long temp = numbers[i];
numbers[i] = randomPosition;
numbers[randomPosition] = temp;
}
for (int i=0; i<name.length; i++)
{
System.out.println("Enter the name: ");
name [i] = input.nextLine();
}
for (int i=0; i<name.length; i++)
{
int randomPosition = id.nextInt(4);
String temp = name[i];
name[i] = randomPosition;
name [randomPosition] = temp;
}
for (int i=0; i<numbers.length; i++)
{
System.out.println(i + " ID = " + numbers[i] + " and name = " + name[i]);
}
}
}

最佳答案

可以获取这些数组并将它们添加到列表中,然后使用集合中的随机播放方法:

Collections.shuffle(List myList);

查看不同问题的相同答案: How can I make this into a loop?

关于java - java中的两个数组打乱顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22035322/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com