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

12 ビュー (過去 30 日間)
Joel Okanta
Joel Okanta 2020 年 10 月 12 日
回答済み: Asad (Mehrzad) Khoddam 2020 年 10 月 12 日
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.

回答 (1 件)

Asad (Mehrzad) Khoddam
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')

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by