Invalidate user entry by using isnan or isempty function

9 vues (au cours des 30 derniers jours)
Sophine Teng
Sophine Teng le 4 Fév 2021
Modifié(e) : Jorg Woehl le 10 Mar 2021
Hi,
How do I invalidate a user entry if a positive number is required from the user but the user type a char or negative value.
when a user type a char or negative value,
a prompt will ask the user to reenter again.
% Check for erroneous input and prompt the user to enter option again
while conversion == 0
conv =str2double(conversion);
conversion = input("\nEnter an option. Yes or No \n", 's');
if isempty(conversion)
fprintf("Option Invalid");
conversion = input("\nEnter an option. DR or RD\n", 's');
elseif isnan(conv)
fprintf("Option Invalid");
conversion = input("Enter an option. DR or RD\n", 's');
elseif conv < 0
fprintf("Option Invalid");
conversion = input("Enter an option. DR or RD\n", 's');
end
end

Réponses (1)

Jorg Woehl
Jorg Woehl le 8 Mar 2021
Modifié(e) : Jorg Woehl le 10 Mar 2021
str2double returns NaN (not-a-number) when it cannot convert text to a number. You can therefore simply use isnan to test if a number has been entered, and combine that with a x>0 check:
str = input('Enter an option: ', 's');
x = str2double(str);
while isnan(x) || ~(x>0)
str = input('Invalid input. Enter an option: ', 's');
x = str2double(str);
end

Catégories

En savoir plus sur Numeric Types dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by