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

标签 java arrays random

抱歉,我是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/

相关文章:

python - 如何使用某种 "momentum"生成随机方向(N、S、E、W、无)?

java - 我的 2d Android 游戏遇到问题

c++ - 如何使用 Armadillo 在不同的计算机上创建相同的随机数?

java - Lombok 和斯波克 : @RequiredArgsConstructor doesn't hide default no-args constructor for a field with a type of interface

java - 使用 AspectJ 递归

arrays - 获取数组中恰好低于匹配值的元素

c - 在 C 中使用 malloc 动态创建一个二维指针数组

java - Weblogic启动失败java.lang.NoClassDefFoundError : weblogic/Server

java - Android:子字符串和 IF

ios - 如何使用循环访问对象数组的每个属性?