如何随机播放ArrayList

时间:2013-04-19 19:51:55

标签: java list collections

我需要一些帮助来编写一个将洗牌ArrayList的方法。我无法弄清楚在我的方法中放置什么。这是我到目前为止所拥有的。我尝试使用随机方法随机化列表中的整数,但这不起作用。有人能告诉我怎么做吗?

以下是我尝试过的代码:

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;
  }
}

2 个答案:

答案 0 :(得分:177)

Collections.shuffle(arrayList);

答案 1 :(得分:29)

尝试Collections.shuffle(list)。如果禁止使用此方法解决问题,那么可以查看实际的实现。