How to add multiple if statements

4 次查看(过去 30 天)
So i was trying to do an age calculator, so i wanted it to detect strings and numerical value, then if it detected a string it will message that ' it is invalid', but if the inputed value is in numerical, but since im still on the days of the month i wanted to limit all value inputed below 31 days and if the user input greater than 31 it will also message an error. i already had progress with the code detecting if it is a string or number, but the problem is the detecting if the number inputed is below 31
So here is the code
function [day]=bdaycalcu
disp ('What day did you born?');
day= (' ');
BdayDate= input (day, 's');
%this part detects if the user input a string or a value
if ~isnan(str2double(BdayDate))
%if the user input a value, it will also detect if it is below 31, if it is go to bmonthcalcu function
bmonthcalcu;
%if the user input a string it will ask again
else
disp('This is not a valid answer')
bdaycalcu;
end
end

采纳的回答

Geoff Hayes
Geoff Hayes 2021-2-12
Jan - I think that you just need to add a couple of conditions to your if statement. You would need to check that the input is numeric (which you are doing) AND is an integer (see isinteger) AND is greater than 0 AND less than our equal to 31. You can use a logical operator found here to AND your conditions.
  2 个评论
Jan Kyle Dismas
Jan Kyle Dismas 2021-2-12
i see its about logic, now i have a problem, because when i do this
function [day,a,b,c,d]=bdaycalcu
disp ('What day did you born?');
day= (' ');
BdayDate= input (day, 's');
a=(~isnan(str2double(BdayDate)));
b=isinteger(BdayDate);
c= a>0;
d=a <= 31;
Since the collection of my values is in terms of strings 's', it would work with logic a since it detects wether theres is NaN which gives 0(false) if they see a string. however it would be a problem for logic b,c and d since the collection of my values would in terms of strings therefore wether i put a numerical or a string it will still give 0(false), is there any ways to get the numerical value out from the user input?
Appreciate your help btw
Jan Kyle Dismas
Jan Kyle Dismas 2021-2-12
yo , nvm i kinda got it, in my previous comment i told that i could not get the numerical value from the input, because ~isnan only detect whether there is a string in the matrix, what i did is to make an variable and use the str2double(BdayDate)) to get the numerical value, isolating the ~isnan to another variable as my logic condition. thank you!!!
% set logical condition
day=(str2double(BdayDate));
a= ~isnan(str2double(BdayDate));
b= day > 0;
c= day <= 31;

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by