0

Random number method

ThiS METHOD RETURNS sAME NUMBER OVER AND OVER. HOW CAN IT BE FIXED TO HAVE A DIFFERENT NUMBER EVERY TIME? using System; public class MainClass { static int Number (){ Random num = new Random(); int xx = num.Next (1,10); return xx; } public static void Main() { for (int i=0; i<10; i++){ Console.WriteLine(Number()+" "); } } }

20th Oct 2019, 1:16 PM
Sharon Keren
Sharon Keren - avatar
3 Respuestas
+ 8
The reason you are getting the same number every time is because your Number() method creates a new Random object on each call. Instead, move the statement which creates the Random object out of the method. using System; public class MainClass { static Random num = new Random(); static int Number (){ return num.Next(1,10); } public static void Main() { for (int i=0; i<10; i++) Console.WriteLine(Number()); } }
20th Oct 2019, 1:24 PM
Hatsy Rei
Hatsy Rei - avatar
+ 1
Great, thank you.
21st Oct 2019, 3:47 AM
Sharon Keren
Sharon Keren - avatar
0
Turn off caps-lock bro. Seriously, I know that it's your IPad's fault, but please fix it
22nd Oct 2019, 4:27 AM
Trigger
Trigger - avatar