Error checking - Identifying non-numerical inputs
6 次查看(过去 30 天)
显示 更早的评论
Hello, I am having some difficulty with a program I'm trying to write (it's a volume calculator). When the user is asked to input a value for, say the radius of a sphere, I would like to give an error message if the value is a non-numerical value(ex. hello, &%%, etc..). There is also an option to enter a range of values and I wanted to make sure there is also an error message if someone does not enter an array for the input.
Here is what I have so far, this is just for one of the functions that calculates sphere volume:
function [ volume ] = sphere( r )
p=imread('sphere.png');
imshow(p)
type = input('Please specify if your input will be a scalar or vector (1 for scalar, 2 for vector): ');
if type == 1
r = input ('Please enter the radius: ');
if isscalar(r)==0
disp('Input must be a scalar. Please try again.')
else
if r < 0
disp ('r cannot be a negative value. Please try again.')
else volume = (4/3)*pi.*r.^3 ;
end
end
elseif type == 2
r = input ('Please enter a range of values for the radius: ');
if ismatrix(r)==0
disp('Input must be a vector. Please try again.')
else
if any(r < 0)
disp ('r cannot contain negative values. Please try again.')
else
fid=fopen('radii.txt','w') ;
fprintf(fid, '%1.2i',r);
fclose(fid);
load radii.txt;
volume = (4/3)*pi.*r.^3;
end
end
else
disp('ERROR. Response is invalid.')
end
end
0 个评论
回答(1 个)
Walter Roberson
2011-11-25
input() in the form you show, always evaluates what the user types as a MATLAB expression, and returns the value of the expression to the program. Therefore if the user types, say, pi/2 then MATLAB will return 1.7<etc> to the program, not the string 'pi/2'.
In order to get the text of what the user typed for error checking purposes, you need to add the 's' option to input:
r = input('Please specify if your input will be a scalar or vector (1 for scalar, 2 for vector): ', 's');
Then, whatever the user types will be returned as a string, which you can then validate, and then use str2double() to convert to numeric form.
7 个评论
Walter Roberson
2011-11-26
NaN returned from str2double() means that str2double() was not able to parse the string as a number. That is a definite problem, and usually means that your code has not properly split the numbers out of their containing string.
Again, set a breakpoint and examine the string carefully and test the conversion of the string from the command line; if you can come up with a sample string that you expect str2double to handle but which it returns NaN for, please post it here.
另请参阅
类别
在 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!