How to make an if condition where strings are involved?

4 ビュー (過去 30 日間)
Roxanne Esguerra
Roxanne Esguerra 2020 年 7 月 5 日
コメント済み: Roxanne Esguerra 2020 年 7 月 5 日
Hi, so this is my code,
alphabet = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
letter = input('Enter a letter: ','s');
count = 0;
while any(strcmp(alphabet,letter));
count = count + 1;
fprintf('Thanks, you enter a %s\n',letter);
letter = input('Enter a letter: ','s');
if letter~=alphabet
fprintf('%d is not a letter\n',letter)
end
end
fprintf('You entered %d letters\n',count);
I need to show that when a nonletter is entered, for example 3, the output will be 3 is not a letter.
I get this error regarding the if condition,
Enter a letter: d
Thanks, you enter a d
Enter a letter: f
Undefined operator '~=' for input arguments of type 'cell'.
Error in printloveletters (line 16)
if letter~=alphabet
What should I put as the if condition to make it work?
Thanks!

採用された回答

madhan ravi
madhan ravi 2020 年 7 月 5 日
編集済み: madhan ravi 2020 年 7 月 5 日
if ~ismember(letter, alphabet)
fprintf('%s is not a letter\n', letter)
end
  1 件のコメント
Roxanne Esguerra
Roxanne Esguerra 2020 年 7 月 5 日
This works! Thank you so much!

サインインしてコメントする。

その他の回答 (2 件)

Alan Stevens
Alan Stevens 2020 年 7 月 5 日
Try replacing
letter~=alphabet
with
~any(strcmp(alphabet,letter))
  1 件のコメント
Roxanne Esguerra
Roxanne Esguerra 2020 年 7 月 5 日
Thanks, I appreciate the help!

サインインしてコメントする。


Sumeet Singh
Sumeet Singh 2020 年 7 月 5 日
if ~ismember(letter,alphabet)
fprintf('%d is not a letter\n',letter)
end
You can't use operator '~=' for operands of type cell (alphabet, a cell array in your case).
  1 件のコメント
Roxanne Esguerra
Roxanne Esguerra 2020 年 7 月 5 日
Thanks, I appreciate the help!

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeMATLAB についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by