3

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?

1
  • 4
    numberGen(1, 7) should be numberGen.Next(1, 7). Refer to the documentation for more. Side note: If you want the user to "press enter", use Console.ReadLine() instead of Console.ReadKey(). The latter will accept any keystroke, not just the Enter key. Commented Mar 31, 2021 at 9:23

3 Answers 3

2

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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.

  • More about Classes in C# here
  • More about Methods in C# here
  • More about Random class here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.