Hi, I am asking the user for input and the input should be either "AA" "Aa" or "aa". How can I validate the input using a while loop? I don't think my code works.Thanks!

3 次查看(过去 30 天)
parentOneA = input("Enter Parent 1's A Trait: ")
% Error checking input
while parentOneA ~= "AA" || parentOneA ~= "Aa" || parentOneA ~= "aa";
parentOneA = input("Enter Parent 1's A Trait: ")
end
  2 个评论
Stephen23
Stephen23 2020-9-24
编辑:Stephen23 2020-9-24
There is no string for which this will return false:
parentOneA ~= "AA" || parentOneA ~= "Aa" || parentOneA ~= "aa";
At least two equality operators will return true, so the output will always be true because you used OR:
true || false || true -> true
Rather than writing them out individually, a better approach is to simply use strcmpi:
while ~strcmpi(parentOneA,'AA')

请先登录,再进行评论。

回答(1 个)

Sindar
Sindar 2020-9-24
You're requiring that it be all valid entries simultaneously
parentOneA = input("Enter Parent 1's A Trait: ")
% Error checking input
while parentOneA ~= "AA" && parentOneA ~= "Aa" && parentOneA ~= "aa";
parentOneA = input("Enter Parent 1's A Trait: ")
end
or
valid_inputs = {'AA';'Aa';'aa'};
parentOneA = input("Enter Parent 1's A Trait: ")
while ~any(strcmp(parentOneA,valid_inputs))
parentOneA = input("Enter Parent 1's A Trait: ")
end

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by