How can i keep repeating the question until they the user makes the correct input?
12 次查看(过去 30 天)
显示 更早的评论
So I created a code that takes in 3 inputs from the user, being "start", "increment" and "stop". The code basically prompts the user to input these numbers through a dialog box. However, I realised that there were problems with the code such as the user making the input for start bigger than the input for stop. I did try to fix this but it ended up causing a broken infinite loop that couldn't be stopped unless Task Manager was whipped out to take it out of its misery.
The code:
%User input for start and stop times
s = 1;
prompt = {'Enter Start time:','Enter increment:','Enter Stop time:'};
title = 'Input';
dims = [1, 35];
answer = inputdlg(prompt,title, dims)
start = str2num(answer{1})
increment = str2num(answer{2})
stop = str2num(answer{3})
if start > stop
while s == 1
error = msgbox('ERROR: Start cannot be larger than Stop time. Try again')
uiwait(error)
disp('Program execution resumed')
answer = inputdlg(prompt,title, dims)
s = 0
end
else
disp('This is legal')
s = 1;
end
I only intended the loop to keep prompting the user to put in an appropriate input until that requirement was met.
0 个评论
回答(1 个)
Asad (Mehrzad) Khoddam
2020-10-12
The start and stop should be defined in the loop as well
%User input for start and stop times
s = 1;
prompt = {'Enter Start time:','Enter increment:','Enter Stop time:'};
title = 'Input';
dims = [1, 35];
answer = inputdlg(prompt,title, dims)
start = str2num(answer{1})
increment = str2num(answer{2})
stop = str2num(answer{3})
while start > stop
error = msgbox('ERROR: Start cannot be larger than Stop time. Try again')
uiwait(error)
disp('Program execution resumed')
answer = inputdlg(prompt,title, dims)
start = str2num(answer{1})
increment = str2num(answer{2})
stop = str2num(answer{3})
end
disp('This is legal')
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!