I need to know why my While Loop is breaking

2 views (last 30 days)
I have the following code. My problem is that once I enter a negative number two consecutive times, instead of repeating the actions within the while loop, the program crashes by giving me an error. Why is this the case and what can I do to remedy my problem?
P=inputdlg('Enter a numeric value for an initial amount of money');
P=cell2mat(P);
P=str2num(P);
while P<0 || ~isnumeric(P)
errordlg('You have made an invalid entry! Please try again.');
P=inputdlg('Enter a numeric value for an initial amount of money');
continue;
end

Answers (1)

Image Analyst
Image Analyst on 21 Dec 2014
This works:
P = -1;
while P<0
caUserInput = inputdlg('Enter a positive numeric value for an initial amount of money');
if isempty(caUserInput),return,end; % Bail out if they clicked Cancel.
% Convert to floating point from string.
usersValue = str2double(caUserInput{1})
% Check for a valid integer.
if isnan(usersValue)
% They didn't enter a number.
% They clicked Cancel, or entered a character, symbols, or something else not allowed.
message = sprintf('I said it had to be a positive number!');
uiwait(warndlg(message));
else
% Else the entry is okay.
P = usersValue;
% But check if it's negative.
if P < 0
message = sprintf('I said it had to be a positive number!');
uiwait(warndlg(message));
else
break;
end
end
end
uiwait(msgbox('Done with while loop'));

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!