+ 3

Simple c# syntax help.

Hello. I have a simple c# game, where user has to guess a number between 1 and 10. There are two functions: Main() and Game() Second function check to see if number inputted equals to the number generated. I get a syntax error stating that there is expected a semicolon at the end which I have placed... Any suggestions? https://code.sololearn.com/cB6XvTaq8T9o/?ref=app

8th Jun 2023, 7:45 PM
Lamron
Lamron - avatar
5 Respuestas
+ 3
Hi Lamron, You made a mistake in line 19: Random int randint = new Random(); // Wrong Random randint = new Random(); // Correct and following this correction, you need to change next lines: /* Line 20 */ randint = randint.Next(0, 10); // Error assigning an int number to a Random variable int randNum = randint.Next(0, 10); // Correct /* Line 22 */ if(num == randint) // Error comparing an int number with a Random variable if(num == randNum) // Correct
8th Jun 2023, 8:26 PM
Artin Azari
Artin Azari - avatar
+ 3
Lamron Random randint = new Random(); create an object. The method Next() create a random number in this claas. In C# you have to define a new variable and thus first will be needed to write int myNewRndNumber = randint.Next(0,10); After you can use the myNewRndNumber how you want as an integer. If you want you could code this task without new variable as follows: if(num == randint.Next(0,10))
8th Jun 2023, 9:11 PM
JaScript
JaScript - avatar
+ 2
The "Random" is a class to generate random numbers with various options, and "Next" method of this class, generates a random "integer" number. So, first you need to instantiate an object from Random class (e.g., Random randomObject = new Random();) Then, you need to create an integer variable to store generated number (e.g., int randomIntegerNumber = randomObject.Next();) If you don't store this int number, you can't use it in following code lines. However, since the random number in this simple program is only used once, you can shorten it as follows: static void Game(int num) { if(num == new Random().Next(0, 10)) { Console.WriteLine("Well done! The guess is correct!"); } . . .
8th Jun 2023, 9:10 PM
Artin Azari
Artin Azari - avatar
+ 2
Artin Azari JaScript , thanks for clarification
8th Jun 2023, 9:32 PM
Lamron
Lamron - avatar
+ 1
Artin Azari , thanks I'll change the code soon. If you don't mind, could you please answer why do we need to assign a new variable to store a result of a function from "Random" class?
8th Jun 2023, 8:34 PM
Lamron
Lamron - avatar