如何洗牌ArrayList [英] How to shuffle an ArrayList

查看:278
本文介绍了如何洗牌ArrayList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一些帮助来编写一个方法,将shuffle 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>();

扫描仪输入= new Scanner(System.in);
System.out.print(输入整数(输入结束为0):);
double value;

do {
value = input.nextDouble(); //从输入中读取一个值

if(value!= 0)
list.add(value); //添加值,如果它不在列表
} while(value!= 0);
System.out.println(最大数目是+ max(list));

System.out.print(输入五个双精度值:);
for(int i = 0; i <5; i ++)
list.add(input.nextDouble());

System.out.println(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 if(result< list.get(i))
result = list.get(i) ;

返回结果;
}

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


解决方案

p> Collections.shuffle(arrayList);


I need some help in writing a method that will shuffle the ArrayList. I can't figure out what to place in my method. Here is what I have so far. I tried using the random method to randomize the integers in the list but that didn't work. Can someone show me how to do this?

Here is the code I've tried:

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

解决方案

Collections.shuffle(arrayList);

这篇关于如何洗牌ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆