how to validate user input between 2 values?
Show older comments
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
More Answers (1)
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
Adam
on 4 Nov 2015
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
Guillaume
on 4 Nov 2015
Do'h! Indeed it does
Categories
Find more on Language Support in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!