MATLAB Answers

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

조회 수: 2(최근 30일)
Breanna Sokolik
Breanna Sokolik 2020년 11월 24일
댓글: Jon 2020년 11월 24일
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??

채택된 답변

Jon
Jon 2020년 11월 24일
편집: Jon 2020년 11월 24일
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
Jon
Jon 2020년 11월 24일
Glad to hear - your welcome

댓글을 달려면 로그인하십시오.

추가 답변(0개)

태그

Community Treasure Hunt

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

Start Hunting!

Translated by