How can i keep repeating the question until they the user makes the correct input?

33 views (last 30 days)
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.

Answers (1)

Asad (Mehrzad) Khoddam
Asad (Mehrzad) Khoddam on 12 Oct 2020
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')

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!