0

First off I want to say that I am still a beginner with C#, so when explaining information to me, please do not use complex jargon that I will not understand. Second, I have done most of the work and I am not asking for others to finish my work, I am just asking for help because I do not understand what is wrong/why it is not working. Third, my program is incomplete, and I cannot finish it unless my random generator is working. So with that being said, the issue that I am having is when I try to run the program, the system underlines the word "random" in the beginning of my code and says

"A field initializer cannot reference the non-static field, method, or property".

Why is it doing this? If I put the two line of code inside "Public Guess()" part then the compiler runs fine, it just then says my "if" statement wont work because the container "random" doesn't exist. I'm not sure of what else I could do and I would really, really, appreciate some help. My code is as follows:

public partial class Guess : Form
{
    /*This is a "Guess the number" program. Then this program is run,
     * I want to create two containers for the "TryParse" portion of this program
     and then I want a number to be randomly generated for the user to guess, then
     I want one last container to count how many guess it took the user.*/

    string number;
    int guess;
    Random random;
    int randomnumber;
    int counter;


    public Guess()
    {
        /*Once the program is initalized, I want the 2nd button hidden until the first one
         is clicked with a value in the textbox*/
        InitializeComponent();
        btnexe2.Hide();
        random = new Random();
        randomnumber = random.Next(0, 101);

    }
    private void btnClose_Click(object sender, EventArgs e)
    {
        //This closes the program//
        Close();
    }
    private void btnexe1_Click(object sender, EventArgs e)
    {
        /*This is where I will be doing most of my variable checking. First, 
         I want to check if the user left the textbox empty, if it is then 
         display a message box saying to enter a number.*/
        if (string.IsNullOrEmpty(tbnumber.Text))
        {
            MessageBox.Show("Please enter a number from 0-100.");
        }
        else
        {/*If it is not empty, then I want the system to determine if the variable 
         that has been entered can be converted to a int.*/
            number = Convert.ToString(tbnumber.Text);
            if (Int32.TryParse(number, out guess))
            {
                /*If the value can be converted, then i want the system to see if
         it is lower, higher, or equal to the random value. Then I want the fist button hidden,
         and the second one shown. Then I want to record how many times the user guessed.*/
                if (guess < randomnumber)
                {
                    btnexe1.Hide();
                    btnexe2.Show();
                    this.BackColor = System.Drawing.Color.LightSeaGreen;
                    lbloutput.Text = "Too Low";
                    counter=counter + 1;
                }
                else if (guess > randomnumber)
                {
                    btnexe1.Hide();
                    btnexe2.Show();
                    this.BackColor = System.Drawing.Color.SlateBlue;
                    lbloutput.Text = "Too High";
                    counter = counter + 1;
                }
                else
                {
                    lbloutput.Text = "Good Guess";
                    counter = counter + 1;
                }
            }
            else
            {
               /*If the value cannot be converted to a int, then display a message box saying so.*/
                MessageBox.Show("This is not a number. Please enter a number between 0-100.");                    
            }
        }
    }
    private void btnexe2_Click(object sender, EventArgs e)
    {/*I want to check if the user left the textbox empty, if it is then 
         display a message box saying to enter a number.*/
        if (string.IsNullOrEmpty(tbnumber.Text))
        {
            MessageBox.Show("Please enter a number from 0-100.");
        }
        else
        {/*If it is not empty, then I want the system to determine if the variable 
         that has been entered can be converted to a int.*/
            number = Convert.ToString(tbnumber.Text);
            if (Int32.TryParse(number, out guess))
            {
                /*If the value can be converted, then I want the system to see if
        it is lower, higher, or equal to the random value. Then I want to record how
                 many times the user guessed.*/
                if (guess < randomnumber)
                {
                    lbloutput.Text = "Too Low";
                    this.BackColor = System.Drawing.Color.LightSeaGreen;
                    counter = counter + 1;
                }
                else if (guess > randomnumber)
                {
                    lbloutput.Text = "Too High";
                    this.BackColor = System.Drawing.Color.SlateBlue;
                    counter = counter + 1;
                }
                else
                {
                    lbloutput.Text = "Good Guess";
                    counter = counter + 1;
                    lblcounter.Text = "You guessed " + counter + " times.";
                }
            }
            else
            {
                /*If the value cannot be converted to a int, then display a message box saying so.*/
                MessageBox.Show("This is not a number. Please enter a number between 0-100");

            }
        }
    }
}
Spr89
  • 81
  • 1
  • 9

4 Answers4

3

Change your code like this. You are trying to call method Next in the class which is not allowed and when you move complete code inside constructor then your variables scope exist only inside that constructor so variable accessed in another method will not work. So solution is to define variable at class level but initialize it in constructor

  Random random; 
  int randomnumber;
    public Guess()
    {
        /*Once the program is initalized, I want the 2nd button hidden until the first one
         is clicked with a value in the textbox*/

        InitializeComponent();
        btnexe2.Hide();
        random = new Random();
        randomnumber = random.Next(0, 101);
    }
Viru
  • 2,228
  • 2
  • 17
  • 28
  • when I do this, my " if " statements become messed up stating that " The name "random" does not exist in the current context. I said this in my original question that was posted. Its driving me nutz! lol – Spr89 Feb 15 '16 at 08:11
  • No,,I guess you are moving the whole code in constructor meaning you are defining the variable in constructor so random variable wont be recognised in another method btnexe2_click ....Can you post the updated answer? – Viru Feb 15 '16 at 08:15
  • Also make sure you use randomnumber instead of random in the if statement – Viru Feb 15 '16 at 08:21
  • Also your tryParse logic is wrong...TryParse returns true on succesful parse so swap your code in if else logic – Viru Feb 15 '16 at 08:21
  • Im not too sure what I did this time to get it to work but it works perfectly now. So i took out the random number generator and set a static value to test everything else. Once that was done I removed the static value and added the random generator back and then viola. I dont understand what I was doing wrong. Is this pure magic? Thank for your help again Viru I really appreciate it, I also thank everyone else for helping me as well. – Spr89 Feb 15 '16 at 17:00
  • It is not magic :p....In the process of setting static value and testing it and reverting the code to use random generator you have corrected the mistake which you were doing earlier (wihtout even noticing it)....it will be really difficult for any of us to explain as we do not know what all code you have touched. Well, Glad your problem is solved. :) – Viru Feb 15 '16 at 17:34
1

You should initialize variables inside a method (initialization means adding a value to a variable - using "new" keyword);

Try something like this:

class Guess {
    Random random;
    int randomNumber;

    public Guess() {
        random = new Random();
        randomnumber = random.Next(0, 101);
        //Rest of the code
    }
}
Artūrs Eimanis
  • 578
  • 3
  • 5
  • 22
  • when I do it your way, all of my errors disappear, and I get 1 new error in place of all the others. Now the system says " Method must have a return type ". would i put " return random " at the bottom of the " public Guess() " method? (i think its a method) – Spr89 Feb 15 '16 at 08:17
  • @Spr89 the `Guess()` is a constructor method. And it doesn't have a return type. You already had a constructor method in your code, in my answer I meant that you should add those 2 initialisation lines to your already existing constructor. – Artūrs Eimanis Feb 15 '16 at 08:23
1

I think this answer can help you. You can not use an instance variable to initialize another instance variable because the order you write them is not per definition the order the compiler creates them.

A field initializer cannot reference the nonstatic field, method, or property

Community
  • 1
  • 1
cverb
  • 645
  • 6
  • 20
0

try changing this

Random random = new Random();
int randomnumber = random.Next(0, 101);

public Guess()
{
    /*Once the program is initalized, I want the 2nd button hidden until the first one
     is clicked with a value in the textbox*/
    InitializeComponent();
    btnexe2.Hide();
}

to this

 private Random _Random;
 private int _RandomNumbrer;
 public Guess()
 {

   _Random = new Random();
   _RandomNumbrer = random.Next(0, 101);

   /*Once the program is initalized, I want the 2nd button hidden until the first one
   is clicked with a value in the textbox*/
   InitializeComponent();
   btnexe2.Hide();
}

youre nearly there with what youre trying to do

Simon Price
  • 3,011
  • 3
  • 34
  • 98
  • Its the same with Viru's post when I do this, my " if " statements become messed up. When i use your underscores, i end up getting a whole new world of errors, not too sure how the generator would work without the " int" in it. – Spr89 Feb 15 '16 at 08:14