How can i keep repeating the question until they the user makes the correct input?
조회 수: 9 (최근 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!