【问题标题】:Unable to get random number to be generated every time object is created每次创建对象时都无法生成随机数
【发布时间】:2016-07-28 18:38:48
【问题描述】:

我一遍又一遍地多次创建具有相同参数的对象。该对象有一个随机方法(使用 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;
    }
}

【问题讨论】:

  • 我们可能需要从您的 Edge 类中查看更多信息才能调试此问题

标签: java eclipse random runtime-error


【解决方案1】:

尝试使用 Java Random 及其 nextInt(int bound) 方法。设边界为包含边的列表的长度。这将返回一个介于 0 (含)和绑定排除之间的随机整数。

您现在使用的方法返回一个介于 0 和 1 之间的数字。然后您将结果转换为int。由于您使用的生成器,您似乎没有得到您期望的那种分布。

【讨论】:

    【解决方案2】:

    据我所知,您返回的是 edges.size() 而不是 randEdge。假设您没有更改边数组,您将始终返回相同的内容。

    【讨论】:

    • 对不起,我没有包括我从阵列中移除 rand 边缘的部分等等。让我也包括在内
    • 我能看到向数组添加额外边的方法吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-11
    • 2014-01-05
    • 1970-01-01
    • 1970-01-01
    • 2013-05-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多