I need to know why my While Loop is breaking
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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
0 comentarios
Respuestas (1)
Image Analyst
el 21 de Dic. de 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'));
0 comentarios
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!