If statement error in gui.

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

 采纳的回答

There is no value of "a" which is simultaneously less than 1 and greater than or equal to 300.
if a < 1 | a >= 300 %finds values outside the range [1, 300)
if a > 1 & a <= 300 %finds values inside the range (1, 300]

更多回答(1 个)

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 个评论

Thank you for making the code not complicated. :)
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.

请先登录,再进行评论。

Community Treasure Hunt

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

Start Hunting!

Translated by