If statement error in gui.
Show older comments
Hi, I have an input box so that the user would input a number ranging 1 to 300. if he put more than 300 and less than one error pop out. this is my code:
a = (str2num(get(handles.Th,'String'))
if (a < 1 & a >= 300);
warndlg('Pressing OK will clear memory','!! Warning !!')
end
Accepted Answer
More Answers (1)
Image Analyst
on 20 Mar 2016
You need to wrap that warndlg() inside a uiwait() otherwise it will go blasting past that and execute more code before they can click OK. Here is some code I use to validate an entry and assign a default in case the user entered an invalid entry.
% Ask user for one integer number.
defaultValue = 45;
titleBar = 'Enter an integer value';
userPrompt = 'Enter the integer';
caUserInput = inputdlg(userPrompt, titleBar, 1, {num2str(defaultValue)});
if isempty(caUserInput),return,end; % Bail out if they clicked Cancel.
% Round to nearest integer in case they entered a floating point number.
userValue = str2double(cell2mat(caUserInput));
% Check for a valid integer.
if isnan(userValue)
% They didn't enter a number.
% They clicked Cancel, or entered a character, symbols, or something else not allowed.
userValue = defaultValue;
message = sprintf('I said it had to be an integer.\nI will use %d and continue.', userValue);
uiwait(warndlg(message));
end
Of course one of the modifications you'd do is to, after my "if", add an "elseif" to check on a and warn the user if they did something boneheaded:
elseif (a < 1 || a >= 300)
message = sprintf('a must be between 1 and 300, not %f.', userValue);
uiwait(warndlg(message));
2 Comments
EJ Ardiente
on 21 Mar 2016
Image Analyst
on 21 Mar 2016
You're welcome. I always try to use lots of comments, even for things that I think should be pretty obvious. I wish everyone would use comments, but sadly most people don't.
Categories
Find more on Code Performance in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!