Restrict user string inputs

4 次查看(过去 30 天)
RealA
RealA 2019-4-25
评论: Adam 2019-4-25
Hey guys, just a quick question, how could I ban all characters inputed by the user execpt 'i' and 'm'.
Thanks
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 ~strcmp(y,'i') | ~strcmp(y,'m')%Need help in this line of code
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 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
end
switch y
case 'i'
fahrenheit = (z*9/5)+32
case 'm'
celsius = (z-32)*5/9
end
  1 个评论
Adam
Adam 2019-4-25
y = input('Please enter the letter ''i'' for an imperial output or ''m'' for a metric output: ', 's');
y = validatestring( y, [ "i", "m" ] );
Depends how stupid you have to treat your users though, by giving them new messages repeating exactly what the first message asked them for if they enter something else!

请先登录,再进行评论。

回答(1 个)

M
M 2019-4-25
The problem comes from your conditions:
~strcmp(y,'i') | ~strcmp(y,'m')
This is never true, even if you enter 'i' or 'm'. What you want is to stop when you enter 'i' or 'm', so the criteria to continue the while loop should be the opposite, not 'i' and not 'm':
~strcmp(y,'i') && ~strcmp(y,'m')
This while loop will also stop when you enter 'i' or 'm'

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by