Validating a String Using a While Loop

10 Ansichten (letzte 30 Tage)
Michael Doherty
Michael Doherty am 9 Okt. 2016
Beantwortet: Walter Roberson am 9 Okt. 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?

Akzeptierte Antwort

Walter Roberson
Walter Roberson am 9 Okt. 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

Weitere Antworten (0)

Kategorien

Mehr zu Characters and Strings finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by