how to validate user input between 2 values?

i making a small function that asks the user to give 5 number so it calculates the average of it.
How do i keep the user from putting invalid values, say i want only values between 1 and 100 to count and reask the user if input wrong
as of now i have this
number1 = input('first number: ') %this 4 more times but +1 ofcourse
average = number1+.. /5;
disp('average is: ')
disp(average)
now if the user input is 0 or 101 or 500 something out of boundaries how do i ask the user to put in a valid number?
say number 1 is correct and user get prompt number 2 but types invalid number how do i reask it.
i've googled a bit but most answers dont fit my way.
thanks in advance!

 Accepted Answer

" %this 4 more times but +1 ofcourse". When you have to repeat the same instruction more than once, you should be thinking loop. A for loop is ideal. In addition, that means you only have to write the validation code once.
Similarly, to reprompt the user if the input is not valid you can use a loop. A while loop is ideal for that. While the input is not valid, prompt.
The validation check itself can be done with if
So your algorithm should be:
for loop to count the input number
set a variable (e.g. validinput) to false, to indicate that the input is not yet valid
while input is not valid
prompt user for number, sprintf can help you build the prompt
put number into a vector using the input number as index
if input is valid (see my comment to adam)
set variable to true to indicate that input is valid
end
end
end
calculate mean of input vector

More Answers (1)

Adam
Adam on 4 Nov 2015
Edited: Adam on 4 Nov 2015
validateattributes( number1, { 'numeric' }, { '>=', 1, '<=', 100 } )
will do the validation for you. (You can use 'integer' also in the second set of curly braces if you want the input to always be an integer-valued one).
You will need to catch the exception it throws in a loop though if you want to then do something in response to that like asking the user to input another number and exit the loop if no exception is thrown.
You can find the specific exception identifiers to catch or you can just use a try-catch and react to all exceptions thrown in the same manner.

3 Comments

validateattributes is very useful to validate the input passed to a function. In this case, wrapping it in a try-catch, I'm not sure it's such a good idea. An if statement would make more sense:
if ~(isnumeric(number1) && isscalar(number1) && number1 >= 1 && number1 <= 100)
%reprompt
end
edit: negated the if statement
True, I was beginning to think as I wrote it that something simpler may work better here.
Though I think that statement needs negating to trigger a reprompt
Do'h! Indeed it does

Sign in to comment.

Categories

Products

Community Treasure Hunt

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

Start Hunting!