필터 지우기
필터 지우기

How to restrict user inputs?

조회 수: 20 (최근 30일)
RealA
RealA 2019년 4월 24일
댓글: Adam Danz 2019년 4월 26일
Hey everyone, just wondering how I could restrict certain user inputs. I want my program to accept two inputs, in this case being 'i' and 'm' and if the user were to enter a number or a different string, my script would keep looping the input question until the user enters the correct value. (Essentialy I just need help on where I commented)
y = input('Please enter the letter ''i'' for an imperial output or ''m'' for a metric output: ', 's');
while isempty(y)
disp('Blank is an invalid input you are required to enter a number from the options above!')
y = input('Please enter the letter ''i'' for an imperial output or ''m'' for a metric output: ', 's');
end
while %Need a function that if the user enters a number or string other than i or m, then this loop activates.
disp(' Invalid input,please enter the letter ''i'' for an imperial output or ''m'' for a metric output')
y = input('Please enter the letter ''i'' for an imperial output or ''m'' for a metric output: ', 's');
while isempty(y)
disp('Blank is an invalid input you are required to enter the letter ''i'' for an imperial output or ''m'' for a metric output!')
y = input('Please enter the letter ''i'' for an imperial output or ''m'' for a metric output: ', 's');
end
end
switch y
case 'i'
fahrenheit = (z*9/5)+32
case 'm'
celsius = (z-32)*5/9
end

답변 (1개)

Adam Danz
Adam Danz 2019년 4월 24일
편집: Adam Danz 2019년 4월 26일
inputOK = false;
while ~inputOK
y = input('Please enter the letter ''i'' for an imperial output or ''m'' for a metric output: ', 's');
if ~isempty(y) && ismember(y, {'m', 'i'})
inputOK = true;
end
end
Another option is to use a question dialog box:
answer = questdlg('Please select output type', mfilename, 'imperial', 'metric', 'quit', 'quit');
  댓글 수: 2
Jan
Jan 2019년 4월 26일
A simplification of:
if ~isempty(y) && ismember(y, {'m', 'i'})
inputOK = true;
end
is
inputOK = any(ismember(y, {'m', 'i'});
Adam Danz
Adam Danz 2019년 4월 26일
Smart! Thanks for the improvement.
(add one more closed-parenthesis to avoid error).

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Buffers, Switches, and Counters에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by