Random on the switch statement, why doesn’t it work?

Asked

Viewed 42 times

1

Following the code below, my intention was to randomize the switch to choose between case 1 and 2, after receiving the word "Gamble". It turns out that when I write Gamble, only case 1 is activated (adding up 10 irons), instead of being random between adding up 10 or subtracting 10. What I did wrong ?

            int ferros;          
            string gamble;
            gamble = Console.ReadLine();
            Random rnd = new Random();
            int luck = rnd.Next(1,3);
            bool loop = true;
            while (loop)
            {
              if (gamble == "gamble")
              {
                  switch (luck)
                  {
                    case 1:
                        ferros = ferros + 10;
                        break;
                    case 2:
                        ferros = ferros - 10;
                        break;
                  }
              }
            }
  • 1

    Is this the only code or have you simplified? If you’re testing on one loop, you have to take the new Random() from inside (use only one instance), otherwise you can have an initialization with Seed repeated. It would be nice for the class the way it tested in reality and explain how it did to execute.

  • Good evening Bacco, I was really doing inside a loop, and my mistake actually was not putting int Rng = Rnd. Next(1, 3); and Gamble = Console.Readline(); within the loop. I ended up noticing this error after reading your comment, even being unintentionally, was of great help hahaha. And thanks for the tip of repeated Seed :)

  • I suggest posting in the answer field the solved code explaining what the error was (and marking your answer as accepted), or remove the question, just to not drop pending.

  • It has already been posted in the reply box, however it is only possible to mark my reply as "accepted" after 2 days.

1 answer

3

The error was not having introduced the "system" to randomize within the loop. The solution to the problem is to implement Gamble = Console.Readline(); and the variable int Luck = Rnd.Next(1,3); within the loop, so that the randomization "system" is always repeated.

        int ferros;          
        string gamble;
        Random rnd = new Random();
        bool loop = true;
        while (loop)
        {
         gamble = Console.ReadLine();
         int luck = rnd.Next(1,3);


            if (gamble == "gamble")
            {
              switch (luck)
              {
                case 1:
                    ferros = ferros + 10;
                    break;
                case 2:
                    ferros = ferros - 10;
                    break;
              }
            }
        } //Code

Browser other questions tagged

You are not signed in. Login or sign up in order to post.