I am writing a simple program in Matlab and wondering how best to ensure that the value the user enters is a valid integer.
I am 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 that there must be a better way, because it does not work all the time. I would also like to add ala error checking to the catch try block. I am completely new to Matlab, so any contribution to 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
It seems to work. Is there anything bad about this? isinteger is determined by the accepted answer
source
share