I'm writing a simple program in Matlab and am wondering the best way to ensure that the value a user is inputting is a proper integer.
I'm currently using this:
while((num_dice < 1) || isempty(num_dice))
num_dice = input('Enter the number of dice to roll: ');
end
However I really know there must be a better way, because this doesn't work all the time. I would also like to add error checking ala a try catch block. I'm brand new to Matlab so any input on this would be great.
EDIT2:
try
while(~isinteger(num_dice) || (num_dice < 1))
num_dice = sscanf(input('Enter the number of dice to roll: ', 's'), '%d');
end
while(~isinteger(faces) || (faces < 1))
faces = sscanf(input('Enter the number of faces each die has: ', 's'), '%d');
end
while(~isinteger(rolls) || (rolls < 1))
rolls = sscanf(input('Enter the number of trials: ', 's'), '%d');
end
catch
disp('Invalid number!')
end
This seems to be working. Is there anything noticeably wrong with this? isinteger is defined by the accepted answer
The following can be used directly in your code and checks against non-integer input including empty, infinite and imaginary values:
isInteger = ~isempty(num_dice) ...
&& isnumeric(num_dice) ...
&& isreal(num_dice) ...
&& isfinite(num_dice) ...
&& (num_dice == fix(num_dice));
The above will only work correctly for scalar input. To test whether a multi-dimensional array contains only integers you can use:
isInteger = ~isempty(x) ...
&& isnumeric(x) ...
&& isreal(x) ...
&& all(isfinite(x)) ...
&& all(x == fix(x))
EDIT
These test for any integer values. To restrict the valid values to positive integers add a num_dice > 0
as in @MajorApus's answer.
You can use the above to force the user to input an integer by looping until they succumb to your demands:
while ~(~isempty(num_dice) ...
&& isnumeric(num_dice) ...
&& isreal(num_dice) ...
&& isfinite(num_dice) ...
&& (num_dice == fix(num_dice)) ...
&& (num_dice > 0))
num_dice = input('Enter the number of dice to roll: ');
end
Try this, modify it as needed.
function answer = isint(n)
if size(n) == [1 1]
answer = isreal(n) && isnumeric(n) && round(n) == n && n >0;
else
answer = false;
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With