How can i add a error check to this program such that the input must only be in numbers?
1 次查看(过去 30 天)
显示 更早的评论
I want to add error checks to this program such that the 'value' input must only be in numbers and the program must keep asking the user for input until the user enters valid number instead of letters or symbols for 'value'.
x=input('choose between 1 to 3')
value = input('Enter any value that you want to convert:','s');
switch x
case 1
result= value+20
case 2
result=value+30
case 3
result=value+70
otherwise
end
0 个评论
采纳的回答
Birdman
2018-4-15
编辑:Birdman
2018-4-15
Try this:
x=input('choose between 1 to 3')
while true
value = input('Enter any value that you want to convert:','s');
if ~isnan(str2double(value))
value=str2double(value);
break;
else
errordlg('Wrong type of value entered. Try again.');
end
end
switch x
case 1
result= value+20
case 2
result=value+30
case 3
result=value+70
otherwise
end
The key code is
~isnan(str2double(value))
This converts the value variable to double and isnan function checks whether the conversion resulted in NaN or numeric variable. According to that, the while loop is broken.
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!