Reputation: 97
I'm trying to create a mathematical game with a timer that calculates the number of correct questions within a specific time. Now I'm trying to increment an int
value per button click if the answer is correct.
But it only increment once and sometimes does not increment:
private void button1_Click(object sender, EventArgs e)
{
int x = Randomnumber.Next(12);
int z = Randomnumber.Next(12);
int s = x * z;
int correct = 0;
//int cv = +correct;
textBox2.Text = x.ToString();
textBox3.Text = z.ToString();
if (s == Convert.ToInt32(textBox4.Text))
{
correct += 1;
numbercorrect.Text = correct.ToString();
}
}
Upvotes: 2
Views: 6215
Reputation: 28695
Try look at code bellow:
int correct = 0;
tryParse(numbercorrect.Text, out correct);
So your code must be like:
private void button1_Click(object sender, EventArgs e)
{
int x = Randomnumber.Next(12);
int z = Randomnumber.Next(12);
int s = x * z;
int correct = 0;
int.tryParse(numbercorrect.Text, out correct);
//int cv = +correct;
textBox2.Text = x.ToString();
textBox3.Text = z.ToString();
if (s == Convert.ToInt32(textBox4.Text))
{
correct += 1;
numbercorrect.Text = correct.ToString();
}
Upvotes: 0
Reputation: 2427
Every time the button is clicked, correct
is beging reset to zero.
Try declaring correct
outside of the method.
Upvotes: 0
Reputation: 227
Try this:
private int correct = 0;
private void button1_Click(object sender, EventArgs e)
{
int x = Randomnumber.Next(12);
int z = Randomnumber.Next(12);
int s = x * z;
//int cv = +correct;
textBox2.Text = x.ToString();
textBox3.Text = z.ToString();
if (s == Convert.ToInt32(textBox4.Text))
{
correct ++;
numbercorrect.Text = correct.ToString();
}
You always start your count with 0, and never get the original value. Now the variable holding the data is outside the function and initialized when the form loads.
Upvotes: 1
Reputation: 31077
int correct = 0;
is scoped within the function. Move it outside the function as a class field. That way it will preserve its value instead of being reset to 0
during each click.
Upvotes: 2
Reputation: 31454
You need to move int correct
declaration to class scope. Otherwise with every click, you start with new variable.
Upvotes: 2
Reputation: 31194
your main form(i'm assuming you're using forms) is a class.
What I'd suggest is declaring a variable as a member of your forms class, and using that to hold the number of correct responses.
I'd imagine something like the following;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
int correct;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//insert logic here
correct++;
}
}
}
Upvotes: 2