Validating a String Using a While Loop

10 visualizaciones (últimos 30 días)
Michael Doherty
Michael Doherty el 9 de Oct. de 2016
Respondida: Walter Roberson el 9 de Oct. de 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?

Respuesta aceptada

Walter Roberson
Walter Roberson el 9 de Oct. de 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

Más respuestas (0)

Categorías

Más información sobre Characters and Strings en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by