this question has answer here:
i creating random function give me 4 random values of a,b,c,d , sign(+,-). problem code generates same values , output has a=b=c=d=x x random value generated code. tried put breakpoint , debug it, works fine no problems remove break point same issue occurs. can please tell me going wrong. code follows:
public void randomquestiongenerate() {//all variables(a,b,c,d,sign1,sign2) globally defined random firstno = new random(); = firstno.next(0, 10); random secondno = new random(); texta.text = a.tostring(); b = secondno.next(0, 10); random thirdno = new random(); textb.text = b.tostring(); c = thirdno.next(0, 10); random fourthno = new random(); textc.text = c.tostring(); d = fourthno.next(0, 10); textd.text = d.tostring(); random firstsign = new random(); int x = firstsign.next(0, 2); if(x == 0) { sign1 = "+"; } else if(x == 1) { sign1 = "-"; } textsign1.text = sign1; random secondsign = new random(); int y = secondsign.next(0, 2); if (y == 0) { sign2 = "+"; } else if (y == 1) { sign2 = "-"; } textsign2.text = sign2; }
you should have one instance of random, preferably entire program.
random automatically seeded time-based value when create using default constructor:
initializes new instance of random class, using time-dependent default seed value.
https://msdn.microsoft.com/en-us/library/h343ddh9(v=vs.110).aspx
the problem is, creating 4 instances faster resolution of time-based value. 4 instances being seeded same value. , when called same parameters, each return same value.
because of race conditions this, should keep 1 global instance of random if possible.
Comments
Post a Comment