Invalidate user entry by using isnan or isempty function

8 visualizaciones (últimos 30 días)
Sophine Teng
Sophine Teng el 4 de Feb. de 2021
Editada: Jorg Woehl el 10 de Mzo. de 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

Respuestas (1)

Jorg Woehl
Jorg Woehl el 8 de Mzo. de 2021
Editada: Jorg Woehl el 10 de Mzo. de 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

Categorías

Más información sobre Numeric Types en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by