Azzera filtri
Azzera filtri

How to restrict user inputs?

8 visualizzazioni (ultimi 30 giorni)
RealA
RealA il 24 Apr 2019
Commentato: Adam Danz il 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

Risposte (1)

Adam Danz
Adam Danz il 24 Apr 2019
Modificato: Adam Danz il 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 Commenti
Jan
Jan il 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 il 26 Apr 2019
Smart! Thanks for the improvement.
(add one more closed-parenthesis to avoid error).

Accedi per commentare.

Categorie

Scopri di più su Language Fundamentals in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by