Validating a String Using a While Loop

10 ビュー (過去 30 日間)
Michael Doherty
Michael Doherty 2016 年 10 月 9 日
回答済み: Walter Roberson 2016 年 10 月 9 日
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?

採用された回答

Walter Roberson
Walter Roberson 2016 年 10 月 9 日
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 件)

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by