I am learning c# as a beginner and making a program that gives the user a random number from a dice until it gets a six. Here is my complete code:
using System;
class HelloWorld {
static void Main() {
Random numberGen = new Random();
int roll = 0;
int attempts = 0;
Console.WriteLine("Press enter to roll the die");
while (roll != 6) {
Console.ReadKey();
roll = numberGen(1, 7);
Console.WriteLine("You rolled " + roll);
attempts++;
}
Console.WriteLine("It took you " + attempts + " to roll a six");
Console.ReadLine();
}
}
What am I doing wrong and how can I debug it?
The issue is here:
roll = numberGen(1, 7);
The only time you can use variable(...) syntax is when variable is a typed delegate (in which case the compiler interprets it as variable.Invoke(...)). In all other cases, it is expected that you access some method/property/field/indexer/event via the variable, using one of variable.Foo(...), variable.Foo or variable[index] (or -> in place of . if variable is an unmanaged pointer).
In this case, you want:
roll = numberGen.Next(1, 7);
In your code, you have created a variable named - 'numberGen'. Since its a variable of class 'Random', you need to call a method of this class using this variable like -
numberGen.Next(1,7);
Here 'Next' is a method of class Random, which takes 2 parameters, min value and max value.
The error you were getting was because you were using the variable as a method.
The deafult approach to generate random numbers in rangs:
Random rnd = new Random();
rnd.Next(1, 10);
In your case hust update the variable
roll = numberGen(1, 7);
to:
roll = numberGen.Next(1, 7);
Random - it's a class. Next - it's a method.