필터 지우기
필터 지우기

Invalidate user entry by using isnan or isempty function

조회 수: 3 (최근 30일)
Sophine Teng
Sophine Teng 2021년 2월 4일
편집: Jorg Woehl 2021년 3월 10일
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

답변 (1개)

Jorg Woehl
Jorg Woehl 2021년 3월 8일
편집: Jorg Woehl 2021년 3월 10일
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

카테고리

Help CenterFile Exchange에서 Numeric Types에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by