How to error check a number for strings and blank inputs?
조회 수: 8 (최근 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에서 Foundation and Custom Domains에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!