c# - Logical error of random value -


i created win-form ability generate number 3 labels(label1,label2,label4) , textbox storage , validate value when ever button pressed. problem label4 didn't raise own value when ever answer correctly. code

int num = 0; string temp;         if (textbox1.text == ans.tostring())         {             num++;             temp = "correct answers " + num;               int = rr.next(4), b = rr.next(4);             ans = + b;             label1.text = a.tostring();             label2.text = b.tostring();                        label4.text = temp;             textbox1.focus();             textbox1.selectall();          } 

does label4 never increase own value, or never increase more first time? because latter of 2 options you're doing. @ steps in logic:

int num = 0; string temp; //... num++; temp = "correct answers " + num; //... label4.text = temp; 

no matter how many times answer correctly, label4 can only ever display:

"correct answers 1" 

because always initialize num 0, increment 1, , display it. track how many answers have been given in total?

you'll need integer value in higher scope track that. place depends on lifespans of objects. example, if object in logic exists persists across multiple answers (that is, if same instance in memory , it's not destroyed , re-created), can add class-level member hold value. this:

private int totalcorrectanswers { get; set; } 

then code use value instead of instantiating new 1 each time:

string temp; //... totalcorrectanswers++; temp = "correct answers " + totalcorrectanswers; //... label4.text = temp; 

other options include storing value in static field persist across object life cycles, database persist across application life cycles, etc. depends on how application structured.


Comments