开发者

Obj-C: ++variable is increasing by two instead of one

开发者 https://www.devze.com 2022-12-26 00:21 出处:网络
I am writing a program that asks users yes/no questions to help them decide how to vote in an election.I have a variable representing the question number called questionnumber.Each time I go through t

I am writing a program that asks users yes/no questions to help them decide how to vote in an election. I have a variable representing the question number called questionnumber. Each time I go through the switch-break loop, I add 1 to the questionnumber variable so that the next question will be displayed.

This works fine for the first two questions. But then it skips the third question and moves on to the fourth. When I have more questions in the list, it skips every other question. Somewhere, for some reasons, the questionnumber variable is increasing when I don't want it to.

Please look at the code below and tell me what I'm doing wrong.

Thank you!

Eli

#import "MainView.h"
#import <Foundation/Foundation.h>  

@implementation MainView
@synthesize Question;
@synthesize mispar;

int conservative = 0;
int liberal = 0;
int questionnumber = 1;

- (IBAction)agreebutton:(id)sender { ++liberal; }
- (IBAction)disagreebutton:(id)sender { ++conservative; }

- (IBAction)nextbutton:(id)sender
{
  ++questionnumber;

  switch (questionnumber)
  {
      case 2: Question.text = @"Congress should ....";  break;
      case 3: Question.text = @"It is not fair ...";    break;
      case 4: Question.text = @"There are two ...";    break;
      case 5: Question.text = @"Top quality h...";     break;
      def开发者_开发百科ault:  break;
  }
}  

@end


It's a bit hard to read, if you can copy it exactly how it is in the implementation file and use the code sample feature for posting code snippets.

To answer the previous question

number++;

That just adds 1 to the value.

number+=anotherNumber;

That will add anotherNumber to number, and is a quick way of saying

number = number + anotherNumber;

As for your code, is there a chance that the nextButton method is being called more then once?


does ++ automatically add 1 to the variable or does it add the variable + itsself

so if questionnumber = 1 then does ++questionumber add questionnumber + questionnumber if so it will only work the 1st time and will skip 3 so when questionnumber is 2 you would be adding questionnumber + questionnumber which = 4

I would change to questionnumber = questionnumber + 1 or if the language supports it questionnumber += 1

Where do you set the increment seed for ++ i believe this functionality is typically used with a for loop.

0

精彩评论

暂无评论...
验证码 换一张
取 消