How to stop the for loop once the right input is given. Cannot use break.

4 vues (au cours des 30 derniers jours)
Breanna Sokolik
Breanna Sokolik le 24 Nov 2020
Commenté : Jon le 24 Nov 2020
n=3;
for i=1:n
riddle2prompt='I dont have eyes, but once I did see. Once I had thoughts, but now Im white and empty. What am I? ';
riddle2=input(riddle2prompt,'s');
if strcmpi(riddle2,'Skull')
%Asking the final riddle because the user answered the other two right.
fprintf('\n')
fprintf('*sighs* You arent supposed to get these. Your final riddle is;')
fprintf('\n')
else
%The game ends if answer is wrong.
fprintf('What did I say about not messing up. Get it right, %s!',name)
fprintf('\n')
fprintf('You have 2 more tries.')
fprintf('\n')
if i==2
fprintf('Haha, you only have 1 more tries. Careful.')
fprintf('\n')
fprintf('Your hint for this riddle is; your brain makes its home here.')
fprintf('\n')
end
if i==3
fprintf('Oh no, what did I say. Now youve already failed my game.')
fprintf('\n')
fprintf('Its GAME OVER for you!!')
riddles=false;
end
end %End to an if statement
end
How do I end the for loop if the user answers the riddle correctly, I dont want to use break for this.
Is there another way to do it??

Réponse acceptée

Jon
Jon le 24 Nov 2020
Modifié(e) : Jon le 24 Nov 2020
You could loop with a while statement instead. Set the exit condition on the while statement to be that the answer was wrong or the number of loops is greater than the max allowed (e.g. 3).
So you could have a loop counter that you initialize to zero before the loop and increment inside the loop. Also have a logical variable, call it for example answeredCorrectly. Initialize it as false before the loop.
Inside of the loop set it to true when the user answers correctly, e.g
answeredCorrectly = strcmpi(riddle2,'Skull')
  3 commentaires
Breanna Sokolik
Breanna Sokolik le 24 Nov 2020
This did just what I needed! Thank you so much!
Jon
Jon le 24 Nov 2020
Glad to hear - your welcome

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Just for fun dans Help Center et File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by