how to create an error message when invalid data is input and then prompt to re-enter the data
9 次查看(过去 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
0 个评论
采纳的回答
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 个评论
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
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
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Migrate GUIDE Apps 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!