How can i generate a new random number after one round in c#?

Viewed 52

I have a problem with my programm. I want to write a random number guessing game. I have actually everything but when i ask the user if he/she wants to do it again and he/she says yes, the same number from the 1. round is also in the second round. Like:

  • Write your number down: 90.
  • Great u guessed the number!
  • Do u want to play again [y|n] y.
  • write another Number: 90.
  • Great u guessed the number!

enter image description here

2 Answers

You have to actually call rnd.Next() everytime you want a different random number:

Random rnd = new Random();
Int32 RandomNumber;
for(int i = 0; i < 100; i++)
{
    RandomNumber = rnd.Next(1, 100);
    Console.WriteLine(RandomNumber);
}

I've prepared a little fotnetfiddle for your convenience.

You should generate new random number for each game round:

public static void Main() {
  // wrong place: random value is the same for all rounds
  //int zufallligezahl = new Random().Next(1, 100);
  ...
   
  try {
      do {
           // right place: each game has its own random value
           // In case of .Net 6 put it as
           // ... = Random.Shared.Next(1, 100);
           int zufallligezahl = new Random().Next(1, 100);

           do {
               Console.Write("Erraten Sie die Zahl indem..."); 
           ...
}
Related