Validating a String Using a While Loop
10 views (last 30 days)
Show older comments
Michael Doherty
on 9 Oct 2016
Answered: Walter Roberson
on 9 Oct 2016
I'm stuck in what seems to be an infinite loop while trying to validate an input string. Even if I enter V or C it still displays the "error".
% INPUT user choice for calculating voltage or current
choice = input('\nPlease enter V to calculate volts or C to calculate current: ', 's');
% TEST if user entered V or C
while choice ~= 'v' || choice ~= 'V' || choice ~= 'c' || choice ~= 'C'
choice = input('ERROR! Please enter either V or C: ', 's');
end
I'm relatively new to MATLAB so I apologize in advance if it is messy or not the most efficient way to do this. Any ideas or suggestions?
0 Comments
Accepted Answer
Walter Roberson
on 9 Oct 2016
while ~ismember(choice, 'vcVC')
choice = input('ERROR! Please enter either V or C: ', 's');
end
Or
while choice ~= 'v' && choice ~= 'V' && choice ~= 'c' && choice ~= 'C'
choice = input('ERROR! Please enter either V or C: ', 's');
end
or
while ~(choice == 'v' || choice == 'V' || choice == 'c' || choice == 'C')
choice = input('ERROR! Please enter either V or C: ', 's');
end
0 Comments
More Answers (0)
See Also
Categories
Find more on Characters and Strings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!