2016-07-28 28 views
0

我使用相同的參數多次重複創建一個對象。該對象有一個隨機方法(使用Math.random()),我知道它應該每次都返回一個不同的數字,但是每次在程序中創建該類的新對象並調用該方法時,它會返回相同的價值。我應該如何解決這個問題?無法獲取每次創建對象時生成的隨機數

地方,我調用該方法合同:

for (int i = 0; i < 212000; i++){ 
      Contractions c = new Contractions(a, b); 
      temp = c.contract(); 
      if (temp < min){ 
       min = temp; 
      } 
      if (i%1000 == 0){ 
       System.out.println(min); 
      } 
     } 

方法:

while (vertices.size() > 2){ 
     Edge randEdge = edges.get((int) (Math.random()*edges.size())); 
     vertices.remove(randEdge.getTwo()); 
     for (int i = edges.size() - 1; i >= 0; i--){ 
      if (edges.get(i).getOne() == randEdge.getTwo()){ 
       edges.get(i).setOne(randEdge.getOne()); 
      } 
      if (edges.get(i).getTwo() == randEdge.getTwo()){ 
       edges.get(i).setTwo(randEdge.getOne()); 
      } 
     } 
     edges.remove(randEdge); 
     removeSelfLoops(); 

return edges.size(); 

邊緣種類:

package Contractions; 

public class Edge { 
    Vertex one; 
    Vertex two; 
    public Edge(Vertex one, Vertex two){ 
     this.one = one; 
     this.two = two; 
    } 
    public boolean isEqual(Edge other){ 
     if (other.one == this.one && other.two == this.two){ 
      return true; 
     } 
     if (other.two == this.one && other.one == this.two){ 
      return true; 
     } 
     return false; 
    } 
    public Vertex getOne(){ 
     return one; 
    } 
    public Vertex getTwo(){ 
     return two; 
    } 
    public void setOne (Vertex v){ 
     one = v; 
    } 
    public void setTwo (Vertex v){ 
     two = v; 
    } 
    public String toString(){ 
     return one + "; " + two; 
    } 
} 
+2

一些代碼可能? – Damiano

+1

包含[mcve]。 – erickson

+0

爲了調試這個 –

回答

0

,據我所知,你是返回edges.size()不。假設你沒有改變邊緣數組,你總會返回相同的東西。

+0

,我們可能需要從你的'Edge'類看到更多的東西,對不起,我沒有包含從數組中刪除rand邊緣的部分等等。讓我包括 – kmindspark

+0

我可以看到添加額外的邊緣到數組的方法嗎? –

1

嘗試使用Java Random及其nextInt(int bound)方法。讓邊界是保持邊的列表的長度。這將返回一個0和0之間的隨機整數。

您正在使用的方法現在返回一個介於0和1之間的數字。然後你將結果投射到int。由於您使用的發生器,您似乎沒有獲得您期望的發佈類型。