How to restrict user inputs?

43 vues (au cours des 30 derniers jours)
RealA
RealA le 24 Avr 2019
Commenté : Adam Danz le 26 Avr 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

Réponses (1)

Adam Danz
Adam Danz le 24 Avr 2019
Modifié(e) : Adam Danz le 26 Avr 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 commentaires
Jan
Jan le 26 Avr 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 le 26 Avr 2019
Smart! Thanks for the improvement.
(add one more closed-parenthesis to avoid error).

Connectez-vous pour commenter.

Catégories

En savoir plus sur Language Fundamentals 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