java随机生成器

时间:2012-05-14 12:14:33

标签: java random

我想生成一些随机双打并将它们添加到ArrayList中,但似乎nextDouble()函数每次都返回一个唯一的double,而不是一个新的

Random r = new Random();
ArrayList<Pair> centers = new ArrayList<Pair>();  
ArrayList<ArrayList<Pair>> classes = new ArrayList<ArrayList<Pair>>();  
for (int i=0 ; i < 100; i++) {
    // Random r = new Random ();
    // System.out.println (r.nextDouble ()) ;
    double a = r.nextDouble () * 10;
    double b = r.nextDouble () * 10;
    centers.add (new Pair (a, b ));
    System.out.println (centers);
}               

任何人都可以帮我吗?这是优化的错误吗?

1 个答案:

答案 0 :(得分:4)

我运行了这段代码:

public static void main(String[] args) {
  Random r = new Random();
  ArrayList<Pair> centers = new ArrayList<Pair>();
  for(int i = 0; i < 100; i++ ) {
    double a = r.nextDouble() * 10;
    double b = r.nextDouble() * 10;
    centers.add( new Pair(a, b) );
  }
  System.out.println(centers);
}

这是输出:

[(8.08, 8.06), (9.97, 1.83), (3.83, 3.19), (2.97, 2.51), (9.40, 2.88), (7.78, 2.59), (1.67, 9.07) ...

这不是你想要的吗?仅供参考,这是我使用的Pair课程:

class Pair {
  private final double a, b;
  Pair(double a, double b) { this.a = a; this.b = b; }
  @Override public String toString() { return String.format("(%.2f, %.2f)", a, b); }
}