how to create an error message when invalid data is input and then prompt to re-enter the data

조회 수: 37 (최근 30일)
person_age = input('Please enter persons age')
If person_age < 1
errordlg('Please input valid number','Error')
end
How do I display this error message and then prompt the user to re-enter the person_age?
Many thanks

채택된 답변

JESUS DAVID ARIZA ROYETH
JESUS DAVID ARIZA ROYETH 2019년 11월 14일
person_age = input('Please enter persons age');
while person_age < 1
errordlg('Please input valid number','Error')
person_age = input('Please enter persons age');
end
  댓글 수: 4
Eddie Burns
Eddie Burns 2019년 11월 15일
thank you worked perfectly. Another question how would i say 'only accept the ages 10, 20 or 30' any other number input is invalid, show error message like above
JESUS DAVID ARIZA ROYETH
JESUS DAVID ARIZA ROYETH 2019년 11월 15일
person_age = input('Please enter persons age');
errors={'Please input valid number >1','Please input valid number <=120'};
while person_age < 1 || person_age>120
errordlg(errors([person_age < 1 person_age>120]) ,'Error')
person_age = input('Please enter persons age');
end
values=[10 20 30];
if ~ismember(person_age,values)
error(['only accept the ages ' num2str(values,'%i ')])
end

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Guillaume
Guillaume 2019년 11월 14일
Typical pattern for this is:
value = someinvalidvalue;
while valueisinvalid
value = input('Enter value');
end
Note that your test is extremely incomplete. Any of the following inputs would be considered valid age:
  • NaN
  • [-1, 2]
  • Inf
  • 'abcdef'
  • 5 + 1i*2
You may want to change your test to:
while isnumeric(person_age) || isscalar(person_age) || isreal(person_age) || isfinite(person_age) || person_age < 1
  댓글 수: 1
Eddie Burns
Eddie Burns 2019년 11월 14일
Many thanks for response, it is a simple machine learning database I am being assesed on, I dont think it requires that level of detail.

댓글을 달려면 로그인하십시오.

카테고리

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

태그

제품


릴리스

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by