User input with 3 options, how to repeat question if one of the options was not entered.

1 次查看(过去 30 天)
I am trying to add something to the end of a function that will be looped over and over to ask the user whether they are happy with the results, at which they can type 'yes', 'no', or 'trash'. If the user types something else the question should be repeated until one of these options is entered. I tried to use the code:
UI = 'aaa'
while UI ~= 'yes' & UI ~= 'no' & UI ~= 'trash' %ERROR AT THIS LINE
UI = input("Are you happy with this? Enter: 'yes' 'no'(to manually change) or 'trash' skip and move onto next unit.", 's')
end
if UI == 'yes'
% do something
return
elseif UI == 'no'
% do something
else UI == 'trash'
% do something else
end
I have tried the while loop with both '&' and '&&' and neither works, was wondering if anyone could help me out, thanks.

采纳的回答

Geoff Hayes
Geoff Hayes 2017-6-24
Sean - use strcmpi when comparing strings else you will see errors like
Error using ~=
Matrix dimensions must agree.
when comparing strings like how you are doing. Your code would then become
UI = [];
while ~strcmpi(UI,'yes') && ~strcmpi(UI,'no') && ~strcmpi(UI,'trash') %ERROR AT THIS LINE
UI = input('Are you happy with this? Enter: ''yes'' ''no''(to manually change) or ''trash'' skip and move onto next unit.', 's');
end
Note how single quotes are used (instead of double quotes) to wrap your string and that we use two single quotes on either side of (say) yes so that the single quotes appear in the output string.
Try the above and see what happens!

更多回答(1 个)

Image Analyst
Image Analyst 2017-6-24
Then don't do it that way. Use questdlg() like you're supposed to:
promptMessage = sprintf('Do you want to Continue processing,\nor Quit processing?');
titleBarCaption = 'Continue?';
buttonText = questdlg(promptMessage, titleBarCaption, 'Continue', 'Quit', 'Continue');
if strcmpi(buttonText, 'Quit')
return; % or break or continue - whatever is appropriate.
end

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by