How do l let the user re-enter input if the original input is unacceptable?

조회 수: 1 (최근 30일)
Everything works so far but I want to make my code so that the user can reenter the grade if he/she enters a grade too high or too low the first time. Here is my code so far:
HW_Grades = []
for jj = 1:4
HW_Prompt = input('What are your grades on your 1st-4th HW assignments? (Enter a number between 5 and 15, then press enter, and repeat); ');
if (HW_Prompt < 5);
disp('Your grade is too low');
end
if (HW_Prompt > 15);
disp('Your grade is too high');
end
HW_Grades(jj) = HW_Prompt;
end
HW_Total = sum(HW_Grades)

채택된 답변

Image Analyst
Image Analyst 2018년 11월 13일
Use a while loop. Try this:
HW_Grades = [0,0,0,0]; % Initialize
for jj = 1 : 4
gradeOK = false;
while ~gradeOK % Keep looping and asking until the grade is OK
userPrompt = sprintf('What is your grade on HW assignment %d?\n (Enter a number between 5 and 15, inclusive, then press enter, and repeat); ', jj);
userResponse = input(userPrompt);
if userResponse < 5
uiwait(warndlg('Your grade is too low'));
elseif userResponse > 15
uiwait(warndlg('Your grade is too high'));
else
HW_Grades(jj) = userResponse;
gradeOK = true;
end
end
end
HW_Total = sum(HW_Grades)

추가 답변 (1개)

madhan ravi
madhan ravi 2018년 11월 13일
look for goto file exchange which does the same work you require

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

태그

제품


릴리스

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by