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

5 visualizaciones (últimos 30 días)
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??

Respuesta aceptada

Jon
Jon el 24 de Nov. de 2020
Editada: Jon el 24 de Nov. de 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 comentarios
Breanna Sokolik
Breanna Sokolik el 24 de Nov. de 2020
This did just what I needed! Thank you so much!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Just for fun en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by