Using "WHILE" to compare input value with positive integer

조회 수: 1 (최근 30일)
Jose
Jose 2012년 8월 31일
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

채택된 답변

Azzi Abdelmalek
Azzi Abdelmalek 2012년 8월 31일
편집: Azzi Abdelmalek 2012년 8월 31일
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
Jose
Jose 2012년 8월 31일
This is just what I need, thanks a lot :D
Matt Fig
Matt Fig 2012년 8월 31일
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

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Image Analyst
Image Analyst 2012년 8월 31일
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
Jose
Jose 2012년 8월 31일
It looks preety, maybe I use it on the future
Image Analyst
Image Analyst 2012년 8월 31일
편집: Image Analyst 2012년 8월 31일
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/

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by