How to error check a number for strings and blank inputs?

31 views (last 30 days)
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

Answers (1)

Daniel Pollard
Daniel Pollard on 15 Apr 2021
Are you looking for validateattributes or assert? For example,
assert(menu == 1 || menu == 2)
will throw an error if menu is not a number equal to 1 or 2.
  7 Comments
Sourav Anilkumar
Sourav Anilkumar on 16 Apr 2021
Yeah sure:
Error using input
Unrecognized function or variable 'w'.
Error in s3784513_Milestone_2 (line 6)
menu = input('Enter a number to choose a conversion: ')
Pretend thats all red haha
Daniel Pollard
Daniel Pollard on 16 Apr 2021
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.

Sign in to comment.

Categories

Find more on Characters and Strings in Help Center and File Exchange

Products


Release

R2020b

Community Treasure Hunt

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

Start Hunting!