Best way to get user to enter integer in matlab

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

+5
source share
5 answers

, , :

isInteger = ~isempty(num_dice) ...
            && isnumeric(num_dice) ...
            && isreal(num_dice) ...
            && isfinite(num_dice) ...
            && (num_dice == fix(num_dice));

. , , :

isInteger = ~isempty(x) ...
            && isnumeric(x) ...
            && isreal(x) ...
            && all(isfinite(x)) ...
            && all(x == fix(x))

. , num_dice > 0, @MajorApus answer.

, , :

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
+7

, .

function answer = isint(n)

if size(n) == [1 1]
    answer = isreal(n) && isnumeric(n) && round(n) == n &&  n >0;
else
    answer = false;
end
+6

/ validateattributes. , ; , , , , , , .

, , , , try-catch :

invalidInput = true;
while invalidInput
  num_dice = input('Enter the number of dice to roll: ');
  try
    validateattributes(num_dice, {'numeric'}, ...
                       {'scalar', 'integer', 'real', 'finite', 'positive'})
    invalidInput = false;
  catch
    disp('Invalid input. Please reenter...');
  end
end

, inputParser.

+2

sscanf (http://www.mathworks.com/help/techdoc/ref/sscanf.html), , .

0

. , :)

% Assume false input at the beginning
checkDice = 0;  

% As long as the input is false, stay in the loop
while ~checkDice
    % Take the input as a string
    strDice = input('Enter the number of dice to roll: ', 's');
    % Convert string to number
    dice = str2num(strDice);

    % Length of dice will be 1 iff input is a single number
    if length(dice) ~=1
        checkDice = 0;
    else
        % Search for a positive integer
        checkDice = ((dice>=1) && dice == floor(dice));   
    end

end
-1

All Articles