java - 如何打乱数组的内容

标签 java arrays random shuffle

所以我的程序应该访问一个文本文档,然后执行所有当前有效的爵士乐。我想不通的唯一问题是如何洗牌数组的内容而不让它们最终相互重叠。互联网和随机和 for 循环的多次尝试都没有结果。这是我的代码:

import java.io.*;
import java.util.*;
public class lab_6 {
public static void main(String[] args)throws FileNotFoundException {
    Scanner input = new Scanner(System.in); //reads from keyboard
    System.out.println("What is the name of your file. ");
    String name = input.nextLine();
    Scanner reader = new Scanner(new File(name));// Open text file
    System.out.println("how many names are in your array");
    int num = input.nextInt();
    String[] names = new String[num];    
    for (int index = 0; index< names.length; index++)
    {
        names[index] = reader.nextLine();// Gets a line while there is one 
    } 
    System.out.println("\nOriginal List");
    printList(names);
    System.out.println("\nShuffled List");
    shuffle(names);
    printList(names);
    System.out.println("\nSorted List");
    Arrays.sort(names);  // this is a built in method
    printList(names);
    System.out.println("What name are you looking for");
    Scanner input1 = new Scanner(System.in); //reads from keyboard
    String find = input1.nextLine();
    int index = search(names,find);
    if(index == -1)
        System.out.println("The name was not there");
    else
        System.out.println(find+" was found at position "+index);
    System.out.println("The average length of all the names is "+averageLength(names));
}
public static void printList(String[] array) // print the list of names numbered
{
    for (int i=0; i<array.length; i++)
    {
        System.out.println((i+1)+") "+ array[i]);
    }

}
public static void shuffle (String[] array) // mix-up the array
{


}
public static int search(String[] array, String find) 
{   
    for(int i=0; i<array.length; i++) {

        if (array[i].equals(find) ) return i;

    } 
    return -1;
}
public static double averageLength(String[] array) //return the average length of the names 
{       
    int sum=0;
    for (int i=0; i<array.length; i++)
    {
        int l= array[i].length();
        sum +=l;
    }
    int average = sum/(array.length);
    return average; 

}

}

最佳答案

String[] names = ...;
Collections.shuffle(Arrays.asList(names));
// done

请注意,Arrays.asList() 返回一个可修改(但固定长度)的列表,由数组支持,而不是数组的副本。因此数组将被打乱。

关于java - 如何打乱数组的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22312827/

相关文章:

C 在动态二维字符数组中插入字符串或(char*),段错误

java - 如何使用 Android Studio 2.1.3 从 Android 中的文本文件中获取随机行?

Python生成具有随机步长的范围数组

java - 在 Eclipse 中重用另一个 Java 项目中的类的最佳方法是什么?

java - 如何等到用户关闭框架才能运行其余代码?

java - Maven 未运行 JUnit 5 测试

php - "$this->array[]()"是什么意思?

java - 如何启动 FlutterActivity 并更改路由

java - 在数组列表中分隔逗号分隔的值,然后将其放回一起

java - 为什么要编写自己的随机数生成器?