Using "WHILE" to compare input value with positive integer

3 visualizaciones (últimos 30 días)
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

Respuesta aceptada

Azzi Abdelmalek
Azzi Abdelmalek el 31 de Ag. de 2012
Editada: Azzi Abdelmalek el 31 de Ag. de 2012
a=-1;
while abs(a)/ceil(a)~=1
a=input('How many items?');
end
%if you allow nul value
a=-1;
while abs(a)~=ceil(a)
a=input('How many items?');
end
  2 comentarios
Jose
Jose el 31 de Ag. de 2012
This is just what I need, thanks a lot :D
Matt Fig
Matt Fig el 31 de Ag. de 2012
Azzi's code works great, but just to answer your question for a more general case, I show some code below. Note that it is best to tell the user what is going on when you have them repeating something.
a = input('How many items? '); % Ask the user first.
% Only if user fails, go into loop with more instructions...
while (a<1) || ceil(a)~=a % Note the use of the OR symbol
a = input('How many items? (Must be a positive integer!) ');
end

Iniciar sesión para comentar.

Más respuestas (1)

Image Analyst
Image Analyst el 31 de Ag. de 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 comentarios
Jose
Jose el 31 de Ag. de 2012
It looks preety, maybe I use it on the future
Image Analyst
Image Analyst el 31 de Ag. de 2012
Editada: Image Analyst el 31 de Ag. de 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/

Iniciar sesión para comentar.

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by