如何洗牌数组列表

我需要一些帮助,在编写一个方法,将洗牌的数组列表。我不知道该在我的方法中加入什么。这是我目前掌握的情况。我尝试使用随机方法对列表中的整数进行随机化,但是没有用。有人能告诉我怎么做吗?

下面是我试过的代码:

import java.util.ArrayList;
import java.util.Scanner;


public class Lab 11 {
public static void main(String[] args) {
ArrayList<Double> list = new ArrayList<Double>();


Scanner input = new Scanner(System.in);
System.out.print("Enter integers (input ends with 0): ");
double value;


do {
value = input.nextDouble(); // Read a value from the input


if (value != 0)
list.add(value); // Add the value if it is not in the list
} while (value != 0);
System.out.println("The maximum number is " + max(list));


System.out.print("Enter five double values: ");
for (int i = 0; i < 5; i++)
list.add(input.nextDouble());


System.out.println("The sum is " + sum(list));


}


public static Double max(ArrayList<Double> list) {
if (list == null || list.size() == 0)
return null;


double result = list.get(0);
for (int i = 1; i < list.size(); i++)
if (result < list.get(i))
result = list.get(i);


return result;
}


public static double sum(ArrayList<Double> list) {
double sum = 0;
for (int i = 0; i < list.size(); i++)
sum += list.get(i);
return sum;
}
}
154516 次浏览

Use this method and pass your array in parameter

Collections.shuffle(arrayList);

This method return void so it will not give you a new list but as we know that array is passed as a reference type in Java so it will shuffle your array and save shuffled values in it. That's why you don't need any return type.

You can now use arraylist which is shuffled.

Try Collections.shuffle(list).If usage of this method is barred for solving the problem, then one can look at the actual implementation.