Using "WHILE" to compare input value with positive integer
Afficher commentaires plus anciens
I want to make a better code. The user will be asked for a number, if the value is not a positive integer, the program should ask again.
a=-1.5;
while a<0
while a/ceil(a)~=1;
a=input('How many items?');
end
if a<0 a=-1.5; end
end
I think i can simplify the coding, (maybe using some &&, or something like that) I just dont know how. Thanks in advance
Réponse acceptée
Plus de réponses (1)
Image Analyst
le 31 Août 2012
I think this code is pretty robust to various illegal inputs:
% Ask user for a number.
titleBar = 'Enter an integer';
userPrompt = 'Enter a positive integer';
numberOfTries = 0;
while numberOfTries < 20 % Failsafe so we don't get caught in an infinite loop.
numberOfTries = numberOfTries + 1; % Failsafe
caUserInput = inputdlg(userPrompt, userPrompt, 1, {num2str(defaultValue)});
if isempty(caUserInput)
return;
end; % Bail out if they clicked Cancel.
doubleValue = str2double(cell2mat(caUserInput));
if isnan(doubleValue)
% They didn't enter a number.
% They entered a character, symbols, or something else not allowed.
integerValue = defaultValue;
message = sprintf('I said it had to be an integer.\nTry Again.');
uiwait(warndlg(message));
continue;
end
integerValue = int32(doubleValue);
if integerValue < 0
message = sprintf('The integer must be >= 0.\nTry Again.');
uiwait(warndlg(message));
continue; % Try again.
end
% If gets to here, they successfully entered a positive integer.
fprintf('The integer is %d\n', integerValue);
break; % Bail out of loop.
end
2 commentaires
Jose
le 31 Août 2012
Image Analyst
le 31 Août 2012
Modifié(e) : Image Analyst
le 31 Août 2012
I hope so. I hope you learn eventually to write robust code like I do. True it's longer but you'd be surprised how many times users do something unexpected. Not only can they enter some negative number, but what if they enter a string "four" instead of 4. The code you're going to use will throw an error, while mine handles it gracefully, warns the user, and continues on until the user enters the correct response or cancels out. The code doesn't have a failsafe to prevent the user getting stuck in an endless loop, doesn't use a nice dialog box, and doesn't have any way to cancel to break out of the loop other than entering a valid number even if they want to or need to exit. That is what I mean by writing robust code. My code has all those features. Learn to write robust code in advance, instead of having to respond to users asking why your program crashed on them. I recommend you read Loren's "Best Practices for Programming MATLAB": http://blogs.mathworks.com/loren/2012/01/13/best-practices-for-programming-matlab/
Catégories
En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!