How to error check a number for strings and blank inputs?
9 次查看(过去 30 天)
显示 更早的评论
I have some issues with a unit converter program I'm writing. Currently I have error checking code for negative values but I also want it to check for string and blank inputs. what if statments should I add to achieve this? Any other improvements I can make?
I've added a condensed version of my code below, the full version has 6 different conversions.
clear, clc
n = 1;
m = 1;
o = 1;
fprintf('1. Celsius ↔ Fahrenheit \n2. Millilitre ↔ Fluid Ounce')
menu = input('Enter a number to choose a conversion: ')
while n == 1
if (menu < 0)
% string and blank error checking here
elseif menu == 2
disp('Millilitre ↔ Fluid Ounce Converter')
disp('1. Millilitre to Fluid Ounce')
disp('2. Fluid Ounce to Millilitre')
unit = input('What conversion should be performed?: ')
while m == 1
if unit == 1
mil = input('Input a volume in millilitres: ');
while o == 1
% string and blank error checking here
if (mil < 0)
disp('A negative number has been entered')
mil = input('Input a volume in millilitres: ');
else
floz = (mil/29.5735);
fprintf('The volume in fluid ounces is %1.2f\n', floz)
n = 0;
m = 0;
o = 0;
end
end
elseif unit == 2
floz = input('Input a volume in fluid ounces: ');
while o == 1
% string and blank error checking here
if (floz < 0)
disp('A negative number has been entered')
floz = input('Input a volume in fluid ounces: ');
else
mil = (floz*29.5735);
fprintf('The volume in millilitres is %1.2f\n', mil)
n = 0;
m = 0;
o = 0;
end
end
else % string and blank error checking here
disp('An invalid input has been entered')
unit = input('Please enter a valid number: ')
end
end
end
end
0 个评论
回答(1 个)
Daniel Pollard
2021-4-15
assert(menu == 1 || menu == 2)
will throw an error if menu is not a number equal to 1 or 2.
7 个评论
Daniel Pollard
2021-4-16
Ok, so according to the documentation, by default, MATLAB thinks that an input is numerical. Give it something like w and it says "hey! w isn't a number!"
You can tell it to read the input in as a string by default by writing something like
menu = input("Your input here: ", 's')
Then, you can test whether the input can be converted into a number by using code from the top answer to this question.
If it can, convert it to a number using str2num. From there you can check it has other properties you want using commands like isempty.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Characters and Strings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!