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

 채택된 답변

Walter Roberson
Walter Roberson 2016년 3월 20일

0 개 추천

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개)

Image Analyst
Image Analyst 2016년 3월 20일

0 개 추천

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

EJ Ardiente
EJ Ardiente 2016년 3월 21일
Thank you for making the code not complicated. :)
Image Analyst
Image Analyst 2016년 3월 21일
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.

댓글을 달려면 로그인하십시오.

질문:

2016년 3월 20일

댓글:

2016년 3월 21일

Community Treasure Hunt

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

Start Hunting!

Translated by