How do I break while loop

조회 수: 7 (최근 30일)
poor kitty
poor kitty 2021년 6월 5일
댓글: David Fletcher 2021년 6월 5일
Hi guys, I'm new to matlab. I have to following code. I want to break the while loop if enter valid promocode(HAPPY10) and when ask_promocode=='N'. How can I do? sending SOS to all the expert here;'(
Thank you in advace for helping me
ask_promocode=input('Do you have any promocode?Y or N ','s');
if ask_promocode=='Y'
while str_promocode=='HAPPY10'
str_promocode=input('Please enter your promocode=','s');
if str_promocode=='HAPPY10'
fprintf('Congrats!You can have the discount capped at RM5\n');
break
end
else
fprintf('Oh dear, you have enter invalid promocode!\n')
end
elseif ask_promocode=='N'
fprintf('Ohh It is sad to heard that! Dear you may proceed to payment now<3 \n');
break
end
else
fprintf('Hi dear, we can not reach you. Try again!\n');
end
end
  댓글 수: 5
poor kitty
poor kitty 2021년 6월 5일
Thank you so much. It helps a lot! But I did some changes for
if strcmp(ask_promocode,'N')
to
while strcmp(ask_promocode,'N')
fprintf('Ohh It is sad to heard that! Dear you may proceed to payment now<3 \n');
break
end
Once again thank you for your help.It means a lot to me. luv you 3000 <3
David Fletcher
David Fletcher 2021년 6월 5일
Ok - you are using loops like if constucts rather than the normal function of a loop, but whatever works for you.

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

답변 (1개)

Sulaymon Eshkabilov
Sulaymon Eshkabilov 2021년 6월 5일
This has to be removed:
if ask_promocode=='Y'
end
Because "while ... end" loop will take care of this issue that makes a user enter "Y" or "N". This is not very robust though as is, but it works.
The crucial error in your code is that while loop never gets its set condition met, e.g.:
while str_promocode=='HAPPY10'
That can be substituted with:
while isempty(str_promocode) % if a user skips to enter any any answer, then it has to keep asking to input Y or N
str_promocode=input('Please enter your promocode=','s');
...
end
%%
  댓글 수: 1
poor kitty
poor kitty 2021년 6월 5일
Hi, thank you for your response. But when I remove
if ask_promocode=='Y'
it doesn't work :'(
while isempty(str_promocode)
str_promocode=input('Please enter your promocode=','s');
if str_promocode=='HAPPY10'
fprintf('Congrats!You can have the discount capped at RM5\n');
else
fprintf('Oh dear, you have enter invalid promocode!\n');
end
elseif ask_promocode=='N'
fprintf('Ohh It is sad to heard that! Dear you may proceed to payment now<3 \n');
else
fprintf('Hi dear, we can not reach you. Try again!\n');
end
end
Sorry, I can't catch the ball. Can you please explai more about it?

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

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by