How to restrict user inputs?

21 Ansichten (letzte 30 Tage)
RealA
RealA am 24 Apr. 2019
Kommentiert: Adam Danz am 26 Apr. 2019
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

Antworten (1)

Adam Danz
Adam Danz am 24 Apr. 2019
Bearbeitet: Adam Danz am 26 Apr. 2019
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 Kommentare
Jan
Jan am 26 Apr. 2019
A simplification of:
if ~isempty(y) && ismember(y, {'m', 'i'})
inputOK = true;
end
is
inputOK = any(ismember(y, {'m', 'i'});
Adam Danz
Adam Danz am 26 Apr. 2019
Smart! Thanks for the improvement.
(add one more closed-parenthesis to avoid error).

Melden Sie sich an, um zu kommentieren.

Community Treasure Hunt

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

Start Hunting!

Translated by