i have a form with 2 labels initializing random numbers and a text box to check if the answer is correct after adding the two random numbers. The problem i am having is SUBMIT processes the next set of random numbers and so the result is always incorrect. here is the code i have so far.
namespace _2ndGradeMath
{
public partial class Default : System.Web.UI.Page
{
Random random = new Random();
protected void Page_Load(object sender, EventArgs e)
{
lblNum1.Text = random.Next(0, 10).ToString();
lblNum3.Text = random.Next(0, 10).ToString();
int num1 = int.Parse(lblNum1.Text);
int num2 = int.Parse(lblNum3.Text);
lblAnswer.Text = (num1 + num2).ToString();
lblAnswer.Visible = false;
}
protected void Button1_Click(object sender, EventArgs e)
{
if (TextBox1.Text != lblAnswer.Text)
{
Button1.Attributes.Add("onClick", "javascript:alert('Incorrect');");
}
else if (TextBox1.Text == lblAnswer.Text)
{
Button1.Attributes.Add("onClick", "javascript:alert('Correct');");
}
TextBox1.Text = "";
}
}
}
Use IsPostBack to only run the initializing code when the page is initially loaded:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
lblNum1.Text = random.Next(0, 10).ToString();
lblNum3.Text = random.Next(0, 10).ToString();
int num1 = int.Parse(lblNum1.Text);
int num2 = int.Parse(lblNum3.Text);
lblAnswer.Text = (num1 + num2).ToString();
lblAnswer.Visible = false;
}
}
Here's the problem. You are loading new random numbers each time the page loads. That's what the Page_Load function does: it runs each time the page loads which includes every time the page is submitted. So when a user presses submit new random numbers are assigned, which makes his answer wrong. You need to assign random numbers in only two instances:
First, when the page loads for the first time. Which can be done by checking the property IsPostBackis false.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack){
lblNum1.Text = random.Next(0, 10).ToString();
lblNum3.Text = random.Next(0, 10).ToString();
}
.
.
.
}
Second, when the user answers correctly.
else if (TextBox1.Text == lblAnswer.Text)
{
Button1.Attributes.Add("onClick", "javascript:alert('Correct');");
lblNum1.Text = random.Next(0, 10).ToString();
lblNum3.Text = random.Next(0, 10).ToString();
}
Consider adding this code to PreRender:
protected override void OnPreRender(EventArgs e)
{
Session["Answer"] = lblAnswer.Text;
base.OnPreRender(e);
}
and then in the Click grab the answer from Session like this:
if (TextBox1.Text != Session["Answer"])
and bear in mind I'm assuming that you actually want to generate new numbers on every post back with this answer.
Related
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
I'm trying to make a small guessing game where it generates a random number, and the user enters in a number using a TextBox and Button. Currently it is creating the random number and doing everything I want, but every time the user presses submit on the button, it generates a new random number for them to guess
I am very new to ASP.NET type stuff, so my code is probably inefficient and incorrect lol, so I have two particular questions.
How can I improve my code to make it work better/work at all.
Do I need a runner class to make it work, and how would I do so?
public partial class WebPageSeparated : System.Web.UI.Page
{
private int randNum;
private int theirGuess;
public WebPageSeparated()
{
Random randomNum = new Random();
randNum = randomNum.Next(0, 10);
theirGuess = 0;
}
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = "Guessing game! Guess a number between [0,10) to see if you can get it right!";
new WebPageSeparated();
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
theirGuess = Convert.ToInt32(TextBox1.Text);
if (theirGuess != this.randNum)
{
Label1.Text = "Sorry, wrong number. Please try again!";
}
else if(theirGuess == this.randNum)
{
Label1.Text = "Correct! A new number has been generated, go ahead and try to do it again!";
new WebPageSeparated();
}
}
catch (System.FormatException)
{
Label1.Text = "Enter a number [1,10)";
}
}
}
Several things are wrong with your code:
You should never create a new instance of your page (new WebPageSeparated()). A new instance is created every time you navigate to the page (by entering its URL in the browser) and whenever you cause a PostBack (e.g. by clicking an asp:button).
If you want to have some code, which runs only the first time the page is invoked (i.e. not during a PostBack, only when navigating to the page), then you should wrap that code in a if (!IsPostBack) {} block.
Because a new instance of the page is created for each PostBack, you cannot store any state (the random number) in an instance-field of the page. You have to find another place where you store the state, e.g:
in a static field, e.g: private static int randNum
note: this is not recommended, since the static field is shared between all instances of your page (doesn't work if multiple users are on your website at the same time)
in a session variable, e.g. Session["randNum"] = randomNum.Next(0, 10)
in the ViewState of the page, e.g. ViewState["randNum"] = ...
this is what I'd recommend for your sample
in a database
With all these points in mind, your Page_Load method would look something like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Random randomNum = new Random();
randNum = randomNum.Next(0, 10);
ViewState["randNum"] = randNum;
}
else
{
randNum = (int) ViewState["randNum"];
}
Label1.Text = "Guessing game! Guess a number between [0,10) to see if you can get it right!";
}
Also, in the case, the user guesses the correct number, you should generate and store a new random number (as done inside the if (!IsPostBack)).
Finally, some topics you might want to read more about: Page Lifecycle, PostBack, Viewstate, Session-state
The reason is asp.net postback all the data to server for every action performed in the browser. Since you are generating a random number in the constructor your facing this issue. I guesss this will help you.
public partial class WebPageSeparated : System.Web.UI.Page
{
private int randNum;
private int theirGuess;
protected void Page_Load(object sender, EventArgs e)
{
Random randomNum = new Random();
randNum = randomNum.Next(0, 10);
theirGuess = 0;
Label1.Text = "Guessing game! Guess a number between [0,10) to see if you can get it right!";
new WebPageSeparated();
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
theirGuess = Convert.ToInt32(TextBox1.Text);
if (theirGuess != this.randNum)
{
Label1.Text = "Sorry, wrong number. Please try again!";
}
else if(theirGuess == this.randNum)
{
Label1.Text = "Correct! A new number has been generated, go ahead and try to do it again!";
new WebPageSeparated();
}
}
catch (System.FormatException)
{
Label1.Text = "Enter a number [1,10)";
}
}
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.
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)];
...
}
I wrote out a very simple code. I am trying to get it to do two things for me
I want it to continually show the user inputs and what the output would be. Right now it does not. I think this is a problem with my appendtext
should I use a try and catch for error handling? That's if the user enters more than one decimal my code crashes. I would like to know how to make it where it reverts back to one decimal and continues on.
Here is a snippet of my code.
Also to note, only in my addition method did I start the appendtext, since it didn't work and I kept getting stuck I stopped and came here...
private void button10_Click(object sender, EventArgs e) {
textBox1.AppendText(".");
}
private void button3_Click(object sender, EventArgs e) {
c = "+";
num1 = double.Parse(textBox1.Text);
textBox1.AppendText("+");
}
private void button12_Click(object sender, EventArgs e) {
c = "-";
num1 = double.Parse(textBox1.Text);
textBox1.Text = "";
}
private void button13_Click(object sender, EventArgs e) {
c = "*";
num1 = double.Parse(textBox1.Text);
textBox1.Text = "";
}
private void button14_Click(object sender, EventArgs e) {
c = "/";
num1 = double.Parse(textBox1.Text);
textBox1.Text = "";
}
private void button4_Click(object sender, EventArgs e) {
num2 = double.Parse(textBox1.Text);
double result;
if (c == "+") {
result = num1 + num2;
textBox1.Text = result.ToString();
}
When you append "+", the num2 is equal to value1+"+"+value2 or something so try to use this code
private void button4_Click(object sender, EventArgs e) {
double result;
if (c == "+") {
num2 = double.Parse(textBox1.Text.Split('+')[1]);//bad idea but will work
result = num1 + num2;
textBox1.Text = result.ToString();
}
}
also try
private void button4_Click(object sender, EventArgs e) {
double result;
if (c == "+") {
num2 = double.Parse(textBox1.Text.SubString(textBox1.Text.LastIndexOf('+')+1));
result = num1 + num2;
textBox1.Text = result.ToString();
}
}
PS: try catch needed!