While Loop is not ending, just keeps repeating from top

I am trying to create a guessing game where the user chooses from 3 colours, this is my script so far.
colour = {'Red','Green','Blue'}
x=colour{randi(numel(colour))}
guess = 0
while guess ~= 1
guess = input('Guess the colour, is it Red, Green, or Blue? ','s')
if(strcmp(guess,x)==1)
continue
else
display('Incorrect')
end
end
display('Correct')
Forgive my lack of not knowing how to organise this post a little better and thankyou in advance for your answers.

 채택된 답변

James Tursa
James Tursa 2015년 9월 19일
편집: James Tursa 2015년 9월 19일
Some slight changes:
colour = {'Red','Green','Blue'}
x=colour{randi(numel(colour))}; % <-- Added semi-colon so you don't print answer
% guess = 0 <-- don't need this
while( true ) % <-- changed condition
guess = input('Guess the colour, is it Red, Green, or Blue? ','s')
if(strcmp(guess,x)==1)
break; % <-- changed continue to break
else
display('Incorrect')
end
end
display('Correct')

댓글 수: 2

Thanks very much, if you wouldn't mind me asking what is the main difference between 'Break' and 'Continue'?
James Tursa
James Tursa 2015년 9월 19일
편집: James Tursa 2015년 9월 19일
continue means to immediately go to the top of the loop and start the next iteration of the loop.
break means to break out of the loop and start executing at the line immediately after the end of the loop.

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Just for fun에 대해 자세히 알아보기

질문:

2015년 9월 19일

편집:

2015년 9월 19일

Community Treasure Hunt

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

Start Hunting!

Translated by