2014-11-07 7 views
0

Я пытаюсь получить счетчик с именем «Guesses», чтобы сохранить подсчет попыток угадать случайное число и вывести общие попытки угадать номер. Я попытался оставить декларацию счетчика в 0 и 1, и количество попыток угадать всегда 0 или 1. Помощь будет оценена, и я снова опубликую весь рабочий код, как только выяснится. Вот мой код.счетчик попыток в C#

int Answer; // declares the Answer variable outside button event 
    public frmGuess() 
    { // generates random number outside button event so does not change on button click 
     InitializeComponent(); 
     Random rand = new Random(); 
     Answer = rand.Next(100) + 1; // makes it range 1 to 100 
    } 
    private void btnGuess_Click(object sender, EventArgs e) 
    { 
     int UserGuess; 
     int Guesses = 0;  // start counter 
     if (string.IsNullOrEmpty(txtGuess.Text)) // input validation check to make sure not blank and is a whole number integer 
     { 
      MessageBox.Show("Please enter a whole number between 1 and 100"); 
      return; 
     } 
     else 
     { 
      UserGuess = int.Parse(txtGuess.Text); // variable assign and code run 
      Guesses ++; 
      if (UserGuess > Answer) 
      { 
       txtGuess.Text = ""; 
       lblAnswer.Text = "Too high, try again."; 
      } 
      else if (UserGuess < Answer) 
      { 
       txtGuess.Text = ""; 
       lblAnswer.Text = "Too low, try again."; 
      } 
      else 
      { 
       lblAnswer.Text = "Congratulations the answer was " + Answer + "!\nYou guessed the number in " + Guesses + " tries.\nTo play again click the clear button."; //victory statement 
      }//end if 
     } //end if 
    } 
    private void btnClear_Click(object sender, EventArgs e) // clears Answer label and Guess textbox 
    { 
     txtGuess.Text = ""; 
     lblAnswer.Text = ""; 
    } 

    private void btnExit_Click(object sender, EventArgs e) // closes window 
    { 
     this.Close(); 
    } 
} 

} `

+1

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

ответ

0

Сброс счетчика в событии кликов.

int Answer; // declares the Answer variable outside button event 
int Guesses = 0; // declare this outside button event, and initialize it to 0. 
       // initialization will happen when the Form object is created. 

... 

private void btnGuess_Click(object sender, EventArgs e) 
{ 
    int UserGuess; 
    // DO NOT reset the counter here. This line is the culprit that 
    // resets the counter every time you click the button 
    //int Guesses = 0;  // start counter 
    ... 
} 

... 
0

Это вопрос обзорное. В настоящее время вы определяете догадки в вашем обработчике событий, где он сбрасывает счетчик при каждом нажатии кнопки. Если вы определяете его на уровне формы, даже как свойство или переменную-член, эта область позволит переменной сохранить свое значение с помощью нескольких событий нажатия кнопок.

0

Да, действительно! Это позаботилось об этом. Думать, я поместил случайное число за пределы кнопки, но не сделал это на счетчик - глупость. Спасибо всем! Рабочий код является:

{ 
    int Answer; // declares the Answer variable outside button event 
    int Guesses = 0;  // declares counter outside button event 
    public frmGuess() 
    { // generates random number outside button event so does not change on button click 
     InitializeComponent(); 
     Random rand = new Random(); 
     Answer = rand.Next(100) + 1; // makes it range 1 to 100 
    } 
    private void btnGuess_Click(object sender, EventArgs e) 
    { 
     int UserGuess; 
     if (string.IsNullOrEmpty(txtGuess.Text)) // input validation check to make sure not blank and is a whole number integer 
     { 
      MessageBox.Show("Please enter a whole number between 1 and 100"); 
      return; 
     } 
     else 
     { 
      UserGuess = int.Parse(txtGuess.Text); // variable assign and code run 

      Guesses ++; // adds 1 to attempts but doesn't count textbox blank or mistyping 

      if (UserGuess > Answer) 
      { 
       txtGuess.Text = ""; 
       lblAnswer.Text = "Too high, try again."; 
       Guesses++; 
      } 
      else if (UserGuess < Answer) 
      { 
       txtGuess.Text = ""; 
       lblAnswer.Text = "Too low, try again."; 
       Guesses++; 
      } 
      else 
      { 
       lblAnswer.Text = "Congratulations the answer was " + Answer + "!\nYou guessed the number in " + Guesses + " tries.\nTo play again click the clear button."; 
      }//end if 
     } //end if 
    } 
    private void btnClear_Click(object sender, EventArgs e) // clears Answer label and Guess textbox 
    { 
     txtGuess.Text = ""; 
     lblAnswer.Text = ""; 
    } 

    private void btnExit_Click(object sender, EventArgs e) // closes window 
    { 
     this.Close(); 
    } 
} 

} `

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