I need to know why my While Loop is breaking
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(1 个)
Image Analyst
2014-12-21
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!