2016-02-15 2 views
0

Прежде всего, я хочу сказать, что я все еще новичок с C#, поэтому, объясняя мне информацию, не используйте сложный жаргон, который я не пойму. Во-вторых, я проделал большую часть работы, и я не прошу других закончить мою работу, я просто прошу помощи, потому что я не понимаю, что не так/почему она не работает. В-третьих, моя программа неполна, и я не могу закончить ее, если мой случайный генератор не работает. Так что с этим, как говорится, вопрос, который я имею, когда я пытаюсь запустить программу, система подчеркивает слово «случайный» в начале моего кода и говоритГенератор случайных чисел Выпуск

«Поле инициализатор не может ссылаться на нестатическое поле, метод или свойство ".

Почему это делается? Если я поместил две строки кода внутри «Public Guess()», то компилятор работает нормально, он просто говорит, что мой оператор «if» не работает, потому что контейнер «random» не существует. Я не уверен, что еще я могу сделать, и действительно, действительно, ценю какую-то помощь. Мой код выглядит следующим образом:

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"); 

      } 
     } 
    } 
} 

ответ

3

Изменить код, как это. Вы пытаетесь вызвать метод Next в классе, который не разрешен, и когда вы перемещаете полный код внутри конструктора, тогда ваша область переменных существует только внутри этого конструктора, поэтому переменная, доступная в другом методе, не будет работать. Таким образом, решение определить переменную на уровне класса, но инициализировать его в конструкторе

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); 
    } 
+0

когда я делаю это, мой «если» заявления становятся перепутались о том, что "имя„случайного“не существует в текущем контексте. Я сказал, что это в моем оригинальный вопрос, который был размещен. Его вождение me nutz! lol – Spr89

+0

Нет, я думаю, вы перемещаете весь код в конструкторе, что означает, что вы определяете переменную в конструкторе, поэтому случайная переменная не распознается в другом методе btnexe2_click .... Можете ли вы опубликовать обновленный ответ? – Viru

+0

Также сделайте конечно, вы используете randomnumber вместо случайного в выражении if – Viru

0

попробуйте изменить этот

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(); 
} 

к этому

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 почти там с, что ты пытался сделать

+0

То же самое с сообщением Виру, когда я это делаю, мои заявления «если» перепутались. Когда я использую ваши подчеркивания, я получаю совершенно новый мир ошибок, не слишком уверен, как генератор будет работать без «int» в нем. – Spr89

1

Вы должны инициализировать переменные внутри метода (средство инициализации добавление значения переменной - с использованием «нового» ключевого слова);

попробовать что-то вроде этого:

class Guess { 
    Random random; 
    int randomNumber; 

    public Guess() { 
     random = new Random(); 
     randomnumber = random.Next(0, 101); 
     //Rest of the code 
    } 
} 
+0

, когда я делаю это по-своему, все мои ошибки исчезают, и я получаю 1 новую ошибку вместо всех остальных. Теперь система говорит, что «Метод должен иметь тип возврата». я бы поставил «return random» в нижней части метода «public Guess()»? (я думаю, его метод) – Spr89

+0

@ Spr89 'Guess()' является методом конструктора. И он не имеет типа возврата. У вас уже был метод конструктора в вашем коде, в моем ответе я имел в виду, что вы должны добавить эти 2 строки инициализации к уже существующему конструктору. –

1

Я думаю, что этот ответ может помочь вам. Вы не можете использовать переменную экземпляра для инициализации другой переменной экземпляра, потому что порядок, который вы пишете, не соответствует определению, которое создает компилятор.

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

Смежные вопросы