counter for attempts in c# - 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.

Related

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.
}

Getting a second input from same text box

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.

How to get array data from one Click Method to another one

Don't think i could be any newer to coding, so please forgive me for whats about to be asked.
Im currently writing a program that lets the user enter a desired amount of random numbers to be generated by Random via textBox (lets say 15 --> you get 15 random numbers), ranging from 1 to 1000.
When hitting the Button A, those randomized Numbers will be saved in Zahlenarray[](-->with the length of the number entered in the textbox) and displayed in label1.Text.
Then there's a Button B, that, when clicked, should sort the Numbers from Zahlenarray[] via bubblesort and display them in label2.
My problem is now that the second Method (Button B_Click) doesnt have the contents of Zahlenarray from the Button A_Click Method.
Id like to pass this data by ref via the arguments, but fiddling with public void (Object sender, EventArgs e) seems to get me in major trouble.
Can i add arguments after EventArgs e, ... or am i missing another way of getting data out f this "scope" (hope thats the right word)?
Both Methods are in the same class.
part of the code of Button A:
public void Button_Anzeigen_Click(Object sender, EventArgs e)
{
label1.Text = "";
int[] Zahlenarray = new int[Int32.Parse(textBox1.Text)];
Everything from Button B:
private void Button_Sortieren_Click(object sender, EventArgs e)
{
label2.Text = "";
label3.Text = "";
int Speicher;
for (int n = Zahlenarray.Length; n > 0; n--)
{
for (int i = 0; i < n-1; i++)
{
if (Zahlenarray[i] > Zahlenarray[i + 1])
{
Speicher = Zahlenarray[i];
Zahlenarray[i] = Zahlenarray[i + 1];
Zahlenarray[i + 1] = Speicher;
Speicher = 0;
}
}
}
foreach (int i in Zahlenarray)
{
label2.Text += i + " ";
if ((i % 9 == 0) && !(i == 0))
label2.Text += "\n";
}
}
Put your array declaration outside of your buttona click handler so you can reference it inside your button b handler.
int[] Zahlenarray;
public void Button_Anzeigen_Click(Object sender, EventArgs e)
{
label1.Text = "";
Zahlenarray = new int[Int32.Parse(textBox1.Text)];
...
}

C# Clearing Array not clearing not sure why

I wrote this program using Arrays in C#. It's homework. I pretty much have everything written in the program but I am stuck on clearing the array. I thought I had it but I don't understand where it's not working.
The program is pretty straightforward. The user enters a score and hits the "add" button. Then the user can enter more scores (anything 0 to 100). If the user chooses "Display" the program will sort the entered scores and display them in a messagebox (done)
if the user presses the "Clear Scores" button the program should clear out the scores. I have it written to clear the text boxes, and I also wrote in there "Scores.Clear();" (Scores being the name of my list array) and then I returned the focus back to my scores entry text box so the user can enter another score.
The book I am using simply says to clear type NameOfList.Clear(); so I'm stuck on why it's not clearing. I can tell it isn't because if I type more scores it will add the total instead of restarting.
Here is my full program code. My clear starts about halfway down.
Thank you in advance.
{
public partial class frmScoreCalculator : Form
{
//declare a list array for scores
List<int> Scores = new List<int>();
//set total and average to 0
int Total = 0;
decimal Average = 0;
public frmScoreCalculator()
{
InitializeComponent();
}
//calculate the average by dividing the sum by the number of entries
private decimal CalculateAverage(int sum, int n)
{
Average = sum / n;
return Average;
}
private void frmScoreCalculator_Load(object sender, EventArgs e)
{
}
//closes the program. Escape key will also close the program
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
//clears the text boxes, clears the array, returns focus back to the score text box like a boss.
private void btnClear_Click(object sender, EventArgs e)
{
txtScore.Text = "";
txtCount.Text = "";
txtTotal.Text = "";
txtAverage.Text = "";
Scores.Clear();
txtScore.Focus();
}
//makes sure the score is within the valid range, calculates the average, adds to the number of
//scores entered, and adds to the total
private void btnAdd_Click(object sender, EventArgs e)
{
if (txtScore.Text == string.Empty)
{
txtScore.Focus();
return;
}
int Score = int.Parse(txtScore.Text);
if (Score > 0 && Score < 100)
{
Scores.Add(Score);
Total += Score;
txtTotal.Text = Total.ToString();
txtCount.Text = Scores.Count.ToString();
Average = CalculateAverage(Total, Scores.Count);
txtAverage.Text = Average.ToString();
txtScore.Text = string.Empty;
txtScore.Focus();
}
// if number is not valid, ask user for valid number
else
{
MessageBox.Show("Please enter a number between 0 and 100.", "ENTRY ERROR, DO IT RIGHT!");
}
// returns focus to txtNumber
txtScore.Focus();
txtScore.Text = "";
}
//display button
private void btnDisplay_Click(object sender, EventArgs e)
{
//sorts the scores low to high
Scores.Sort();
//displays scores in message box
string DisplayString = "Sorted Scores :\n\n";
foreach (int i in Scores)
{
DisplayString += i.ToString() + "\n";
}
MessageBox.Show(DisplayString);
}
}
}
You need to zero the variable Total at the same time as clearing the array.

Categories

Resources