Getting a second input from same text box - c#

I am in a C# class and our assignment is to create a random number generator and have the user guess the number. Once the user makes a guess the program tells the user if it is too high or low, then allows them to modify their guess. It also keeps track of the number of guesses a user has completed.
My issue is that after the first run through it will not allow the user to enter a new guess. It either keeps the first entry or if I clear the entry says it is invalid input. Any and all help is appreciated. Because this is a homework assignment I am required to user certain elements, such as try catch, and a repeating loop such as a for loop, or a do while loop. Thanks for your help.
private void Guess_btn_Click(object sender, EventArgs e)
{
try
{
Random random = new Random();
int Answer = random.Next(0, 99);
int User_Guess = 0;
int Guess_num = 0;
do
{
User_Guess = int.Parse(Guess_txtbx.Text);
Guess_num++;
if (User_Guess < Answer)
{
MessageBox.Show("Your answer is too low, try again.");
Guess_txtbx.Clear();
Guess_txtbx.Focus();
User_Guess = int.Parse(Guess_txtbx.Text);
}
else if (User_Guess > Answer)
{
MessageBox.Show("Your answer is too high, try again.");
Guess_txtbx.Clear();
Guess_txtbx.Focus();
User_Guess = int.Parse(Guess_txtbx.Text);
}
else
{
MessageBox.Show("Your answer is correct! It took you " + Guess_num + "number of guesses.");
}
} while (User_Guess != Answer);
}
catch (Exception ex)
{
//Display error message
MessageBox.Show(ex.Message);
}
}

You use the 'do-while' loop inside the click event handler, it leads to blocking the UI thread and hanging of the entire application.
You can use something like this
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Answer = random.Next(0, 99);
User_Guess = 0;
Guess_num = 0;
}
Random random = new Random();
int Answer;
int User_Guess;
int Guess_num;
private void Guess_btn_Click(object sender, EventArgs e)
{
try
{
User_Guess = int.Parse(Guess_txtbx.Text);
Guess_num++;
if (User_Guess == Answer)
{
MessageBox.Show("Your answer is correct! It took you " + Guess_num + "number of guesses.");
Guess_num = 0;
return;
}
MessageBox.Show(String.Format("Your answer is too {0}, try again.", User_Guess > Answer ? "High" : "Low"));
Guess_txtbx.Clear();
Guess_txtbx.Focus();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
I've checked my code. It running and executing always. You had the one more mistake in your code: you wrote in the click event handler that random number generates with the ever users click on the button then you always had the different numbers and a user couldn't guess the right number at all.

Related

Random number resets every time click event handle executes

Hello I am currently trying to make a guessing game with windows form app in c#. I can not figure out how to make it so my random number only generates one time. For example every time I click my guess button (as shown in guessButton_Click) it generates a different random number. I just want the random number to be generated just once during this code run. How can I accomplish this? Any help is greatly appreciated!
public partial class randomNumberForm : Form
{
Random ranNum = new Random();
int userGuess = 0;
int numberOfGuesses = 0;
public randomNumberForm()
{
InitializeComponent();
}
public void randomNumberForm_Load(object sender, EventArgs e)
{
}
public void guessButton_Click(object sender, EventArgs e)
{
int randomNumber = ranNum.Next(101) + 1;
if (int.TryParse(inputTextBox.Text, out userGuess))
{
if (userGuess < randomNumber)
{
answerLabel.Text = "Too low, try again.";
numberOfGuesses++;
guessLabel.Text = numberOfGuesses.ToString();
}
else if (userGuess > randomNumber)
{
answerLabel.Text = "Too high, try again.";
numberOfGuesses++;
guessLabel.Text = numberOfGuesses.ToString();
}
else if (userGuess == randomNumber)
{
answerLabel.Text = "You guessed the right number!";
numberOfGuesses++;
guessLabel.Text = numberOfGuesses.ToString();
}
}
else
{
MessageBox.Show("Please enter a valid integer.");
}
}
Look at where you've placed the line int randomNumber = ranNum.Next(101) + 1; - it's the very first thing your button click event does, and it will run every single time the button is clicked.
Declare your randomNumber variable at the top of the class as a private int. This will make it a class variable which is only accessible from within the class itself.
Move your line of code randomNumber = ranNum.Next(101) + 1; into the randomNumberForm_Load function. This will populate the randomNumber variable on the form load event.
You must have a global variable.
see the example below
public partial class randomNumberForm : Form
{
Random ranNum = new Random();
int userGuess = 0;
int numberOfGuesses = 0;
int? randomNumber;
public randomNumberForm()
{
InitializeComponent();
}
public void randomNumberForm_Load(object sender, EventArgs e)
{
}
public void guessButton_Click(object sender, EventArgs e)
{
if (!randomNumber.HasValue) // first time run
randomNumber = ranNum.Next(101) + 1;
if (int.TryParse(inputTextBox.Text, out userGuess))
{
if (userGuess < randomNumber)
{
answerLabel.Text = "Too low, try again.";
numberOfGuesses++;
guessLabel.Text = numberOfGuesses.ToString();
}
else if (userGuess > randomNumber)
{
answerLabel.Text = "Too high, try again.";
numberOfGuesses++;
guessLabel.Text = numberOfGuesses.ToString();
}
else if (userGuess == randomNumber)
{
answerLabel.Text = "You guessed the right number!";
numberOfGuesses++;
guessLabel.Text = numberOfGuesses.ToString();
}
}
else
{
MessageBox.Show("Please enter a valid integer.");
}
}

A program that tutors the user with Addition

I am creating a C# application that generates two random integers,between 100 to 500. The numbers should perform addition such that
247 + 129 = ?
The form has a text box for the user to enter the problem's answer. When a button is clicked, the application should do the following:
Check the user's input and display a message indicating whether it is the correct answer or not.
Generate two new random numbers and display them in a new problem on the form
add a button named "Save score to file".
When clicked, this button should write the total number of problems, the number of correct answers as well as the percentage of problems answered correctly.
Code:
InitializeComponent();
Random rand = new Random();
{
int number1;
number1 = rand.Next(400) + 100;
numberLabel1.Text = Convert.ToString(number1);
}
{
int number2;
number2 = rand.Next(400) + 100;
numberLabel2.Text = Convert.ToString(number2);
}
}
private void checkButton_Click(object sender, EventArgs e)
{
int correctAnswer;
correctAnswer = int.Parse(numberLabel1.Text) + int.Parse(numberLabel2.Text);
int userAnswer;
userAnswer = Convert.ToInt32(userInputBox.Text);
if (userAnswer == correctAnswer)
{
MessageBox.Show("Your Answer is Correct");
}
else
{
MessageBox.Show("Your Answer is Incorrect");
}
}
private void clearButton_Click(object sender, EventArgs e)
{
numberLabel1.Text = "";
numberLabel2.Text = "";
userInputBox.Text = "";
}
private void exitButton_Click(object sender, EventArgs e)
{
this.Close();
}
private void answerBox_TextChanged(object sender, EventArgs e)
{
}
}
}
The question I have is: How do I get an output? The message box isn't showing and I answer the problem correctly each time. After This how do Generate two new random numbers and display them in a new problem on the form add a button named "Save score to file".
When clicked, this button should write the total number of problems, the number of correct answers as well as the percentage of problems answered correctly.
private static Random rand = new Random();
private void checkButton_Click(object sender, EventArgs e)
{
int num1 = rand.Next(400) + 100;
int num2 = rand.Next(400) + 100;
label1.Text = num1.ToString();
label2.Text = num2.ToString();
int correctAnswer = num1 + num2;
int userAnswer = Convert.ToInt32(textBox1.Text);
if (userAnswer == correctAnswer)
{
MessageBox.Show("Your Answer is Correct");
}
else
{
MessageBox.Show("Your Answer is Incorrect");
}
}
[First]
Console.WriteLine ( String.Format("Answer => " + userAnswer ) );
will show it on console window
MessgeBox.Show( ( String.Format("Answer => {0}", userAnswer ) );
will show it on MessageBox.
I put 2 types of how to use String.Format for you :)
[Second]
you can make a button which do the task again.
put your generating code under the button function
[Third]
You need to study about StreamWriter

new to programing trying to make a number guessing game in c#

Hi so I am new to programing I just started school and I wanted to get a head start on programing so please keep in mind that everything I show you is all self-taught. Here is my question I wanted to make a random number guessing game and for the most part it works but every time you click the button to guess it randoms a different number which I don’t want here is what I have so far
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// number of guesses
int numberOfGesses = 0;
private void btnCalc_Click(object sender, EventArgs e)
{
// make the generator
Random generator = new Random();
//make the number
int number = generator.Next(1, 10);
// get the users guess
int guess = int.Parse(txtInput.Text);
//check the users guess
if (guess == number)
{
lblAnswer.Text = "You got it";
numberOfGesses = 0;
}
else if (guess != number)
{
numberOfGesses = numberOfGesses + 1;
lblAnswer.Text = "try agian you have gessed" + (numberOfGesses) + " times";
}
}
}
I know it keeps creating a new number because every time I press the guess button it starts from the top and makes a new number. I tried to take this block and make it global but I got an error
// make the generator
Random generator = new Random();
//make the number
int number = generator.Next(1, 10);
again im realy new and i found this site when lookinging up some qeustions i had so i thought it would be a good place to help me learn about programing while i wait till i can get into the programing classes thank you for your time.
You likely got an error because C# doesn't allow you to assign a default value of a field based on another field.
public partial class Form1 : Form {
int numberOfGuess = 0;
Random generator = new Random();
int number;
// other methods
}
generator can be initialized before or after number, hence the error. Instead, you can put it in the form intializer (Form1 method), or make another button and click it and generate a new random number:
public partial class Form1 : Form
{
// number of guesses
int numberOfGesses = 0;
Random generator = new Random();
int number;
public Form1()
{
InitializeComponent();
// Generate the random number
number = generator.Next(1, 10);
}
private void btnRandom_Click(object sender, EventArgs e)
{
// Generate a new random number when you click a button on the form
number = generator.Next(1, 10);
}
private void btnCalc_Click(object sender, EventArgs e)
{
// get the users guess
int guess = int.Parse(txtInput.Text);
//check the users guess
if (guess == number)
{
lblAnswer.Text = "You got it";
numberOfGesses = 0;
}
else if (guess != number)
{
numberOfGesses = numberOfGesses + 1;
lblAnswer.Text = "try agian you have gessed" + (numberOfGesses) + " times";
}
}
}
You cannot use an instance variable to initialize another instance variable. Why? Because the compiler can rearrange these - there is no guarantee that generator will be initialized before number, so the above line might throw a NullReferenceException.
So change the default number value to 0:
Random generator = new Random();
int number = 0;
Initialise in the constructor:
public Form1()
{
InitializeComponent();
number = generator.Next(1, 10);
}
When the button is clicked generate the number since here you will be needing it:
private void btnCalc_Click(object sender, EventArgs e)
{
//take the input & Compare as before.
}

counter for attempts in c#

I am trying to get the counter named "Guesses" to keep a tally of attempts at guessing a random number and output the total attempts at guessing the number. I have tried leaving the counter declaration at 0 and 1 and the number of attempts to guess is always 0 or 1. Help would be appreciated and I will re-post entire working code once it's figured out. Here is my code.
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();
}
}
}`
Yes indeed! That took care of it. To think I placed the random number outside the button click but didn't do it to the counter - foolishness. Thanks all! Working code is :
{
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();
}
}
}
`
You are resetting the counter in your click event.
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
...
}
...
It's a scoping issue. You currently define guesses within your event handler where it resets the counter with each button click. If you define it at the form level, even as a property or member variable, that scope will allow the variable to retain its value through multiple button click events.

Using a try catch statement to only allow a user to input an integer into a textbox on Button Click event

Trying to figure out how I can use a try catch statement so that when I click the button to output whether a number is odd or even, an error message will be displayed if I enter a string instead of a number! I know how I'd do it using a bool statement to check if the number is a string, was just interested to see how it would work with a try catch or if it's possible! Any help would be greatly appreciated, thanks in advance!
private void Button_Click(object sender, RoutedEventArgs e)
{
int oddOrEven = 0;
try
{
oddOrEven = Convert.ToInt32(txtNumber.Text);
}
catch
{
tbkOutput.Text = "You must enter a number, please try again";
}
if (oddOrEven % 2 == 0)
{
tbkOutput.Text = "Number is even";
}
else
{
tbkOutput.Text = "Number is odd";
}
}
You shouldn't let exceptions determine program flow. There is no point doing that here when you have functions like int.TryParse:
int output = 0;
if (int.TryParse(txtNumber.Text, out output)) {
// its a number
}
else {
// it isn't a number
}
You shouldn't really implement any logic based on try catch, maybe consider using TryParse
int oddOrEven = 0;
if(!Int32.TryParse(txtNumber.Text, out oddOrEven))
{
tbkOutput.Text = "You must enter a number, please try again";
return;
}

Categories

Resources