0

I hope I can get my problem clear, I appreciate your time.

in my console program it prints 2 variables double random and one String this per line, I repeat the random logic and reprint again,I create 3 Cards, but before "Card card2 = new Card", this saves the values of Atkk, Def, Tipe, in a string that refers to which Card those values belong, and so the 3 print in the Main. but when running it with the start button it always prints something like this:

Atakk:2.33 , Def: 4.66, Tipe: Fire
Atakk:2.33 , Def: 4.66, Tipe: Fire
Atakk:2.33 , Def: 4.66, Tipe: Fire

yes, it's always the same when I close it and try again, obviously the values change, but the same thing is repeated 3 times ...

then I have run it 4 times, step by step (F11), and the result is always very variable:

Atakk:1.33 , Def: 5.10, Tipe: Fire
Atakk:4.64 , Def: 8.69, Tipe: Water
Atakk:0.17 , Def: 9.20, Tipe: Land

Has someone happened same problem, because something like this is given?

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
  • 1
    Possible duplicate of [Random number generator only generating one random number](https://stackoverflow.com/questions/767999/random-number-generator-only-generating-one-random-number) – ProgrammingLlama Sep 06 '18 at 03:09
  • 1
    Tip: You should always include a [mcve] with your question. It allows us to see where you have gone wrong, and give answers that are actually relevant to your question. That being said, since you're talking about _random_, I'm assuming you have made the common mistake detailed in the duplicate I linked. – ProgrammingLlama Sep 06 '18 at 03:11
  • 1
    You are absolutely right, thank you for your comment and for your time. – Sam Leighton Sep 06 '18 at 03:18

2 Answers2

0

This is a guess, but I suspect this it connected with the way you initialize your new Random().

It should be done once, not in a loop.

As Batman@John said please check out Random number generator only generating one random number

tymtam
  • 31,798
  • 8
  • 86
  • 126
0

Because Random classed is initialized based on Clock then sometimes you will meet same numbers. The solution is you should keep same instance of Random and call Next() on the same Random instance to generate your numbers:

    private static readonly Random Random = new Random();
    private static readonly object SyncLock = new object();

    public static int GenerateRandomNumber(int min, int max)
    {
        lock (SyncLock)
        {
            return Random.Next(min, max);
        }
    }

P/S: it 's just an example. In your source code you can define a singleton class or something else for better design.

Happy coding!

Nhan Phan
  • 1,262
  • 1
  • 14
  • 32