Reputation: 183
I'm pretty new to coding and I'm creating a quiz using C#, however i'm running into problems when trying to increment the total score when an answer is answered correctly. the code calling the method is:
private void nextQuestionButton1_Click(object sender, EventArgs e)
{
if (majNugentRadioButton.Checked)
{
// increment total score
Program.Score();
// load question 2
Question2 win2 = new Question2();
win2.Show();
this.Close();
}
else
{
// load question 2
Question2 win2 = new Question2();
win2.Show();
this.Close();
}
}
}
And the code for the Program.Score(); method is:
static public void Score()
{
int totalScore = 0;
totalScore++;
}
When i call this method from the 2nd question it sets the totalScore back to 0, how can i get it so that it only assigns the value of 0 the first time it's called?
Upvotes: 0
Views: 77
Reputation: 162
Declare your TotalScore variable outside the Score() method. If you declare inside the method, when it has been called,the value of TotalScore assigned as 0.
Then Declare the TotalScore as static variable. Because inside the static method, you can access only static members.
Upvotes: 0
Reputation: 125197
If your score method is in your program class, you should create a static TotalScore in program class:
public static class Program
{
private static int TotalScore;
static public void Score()
{
TotalScore++;
}
//... Other stuff
}
In your implementation it's obvious that every time you call Program.Score(), the local variable in Score method setts to 0 and then ++
Important:
Remember that static methods can only access static members, so you should declare TotalScore as static.
Upvotes: 2
Reputation: 175
Every time you call the method Score() you are creating a new variable called totalScore and assigning it a value of 0
to solve this declare the totalScore variable outside the scope of the Score() method so it is not assigned the value of 0 every time you call Score()
int totalScore = 0;
static public void Score()
{
totalScore++;
}
Upvotes: 1