0

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

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

谁能帮我这个?这是优化错误吗?

4

1 回答 1

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); }
}
于 2012-05-14T12:22:27.763 回答