Filter löschen
Filter löschen

I need to know why my While Loop is breaking

1 Ansicht (letzte 30 Tage)
Maroulator
Maroulator am 21 Dez. 2014
Beantwortet: Image Analyst am 21 Dez. 2014
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

Antworten (1)

Image Analyst
Image Analyst am 21 Dez. 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'));

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by