0

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?

2
  • 2
    totalScore is locally scoped to the Score() method which means it only exists within this method. Basically it creates a new variable, assignes it a value of 0, increments it by one, then discards the variable. Commented Sep 7, 2015 at 13:18
  • Declare you totalScore variable as static Commented Sep 7, 2015 at 13:21

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Reza, i knew it would be something simple.
1

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++; } 

1 Comment

My mistake... missed it was static
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.