Question

I am currently writing a program which generates an answer value that is between 1 and 100:

int answer = 0;
answer = arc4random() % 100 + 1;

I begin by having the user guess the value in a field on the screen. The script will then run a simple loop to determine if the value they entered matches the random answer value.

At this point, I have an initial screen which asks for the user’s guess. They type in a number and click a button to submit the value. The problem is that if they do not guess the answer value right from the first entry then the answer value is regenerated and applied to a new random value on each button click.

My question then is how I can have the random value generated at the onset of the view and then maintained until the user has correctly guessed that value.

My attempt was to relocate this:

int answer = 0;
answer = arc4random() % 100 + 1;

to the beginning of the page, but then I get errors showing up stating there is a missing identifier for answer when the method is called later on the page. Thank you for the assistance it is much appreciated.

Était-ce utile?

La solution

I think the issue is because you put the random generation snippet inside your IBAction, as you stated in your comment:

this is the method which takes the value submitted in the field

which means the code inside guessNow:sender will be triggered every time the user clicks on the button, that means you generate a random number every time the user submits a guess which makes no sense.

//this is the method which takes the value submitted in the field and changes the label display after the user clicks the guess now button

- (IBAction)guessNow:(id)sender {

//set the random siri guess value between 1 and 100

int answer = 0;
answer = arc4random() % 100 + 1;

self.usersGuess = self.guessNumberField.text;

you should put that code block inside viewDidLoad() and add a property _answer to your .h

Here is a quick solution, I did not write this on XCode so might have syntax error

in your .h, add

@property (strong) int _answer;

in your .m, remove this from guessNow:sender

int answer = 0;
answer = arc4random() % 100 + 1;

and add this to your viewDidLoad()

answer = arc4random() % 100 + 1;

Also you might want to add another button to reset the random number, so I would say to isolate the random number generation out to a private method like this in your .m

- (void)generateRandomNumber
{
    self.answer = arc4random() % 100 + 1;
}

So that, you can use this method in your viewDidLoad() to generate the initial random number and use it for reset button, if any

hope it helps.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top