Azzera filtri
Azzera filtri

I need to know why my While Loop is breaking

1 visualizzazione (ultimi 30 giorni)
Maroulator
Maroulator il 21 Dic 2014
Risposto: Image Analyst il 21 Dic 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

Risposte (1)

Image Analyst
Image Analyst il 21 Dic 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'));

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by