Logical operator for strings

조회 수: 25 (최근 30일)
Lingbai Ren
Lingbai Ren 2021년 9월 15일
댓글: Lingbai Ren 2021년 9월 24일
I am writing the code for rock, paper, and scissors.
I want to ask users' input, if it's rock, paper, or scissors, I want to store the value to user_choice
if the input is anything else, it will just display an error message.
my code is below, does not matter what I put in for the input, it always go through both if and else section, can anyone explain or help to fix it please?
prompt = 'rock(r),paper(p),or scissors(s)? Make a choice!';
user_choice = input(prompt,'s')
if user_choice == 'r'|user_choice =='p'|user_choice =='s'
fprintf('Your choice is %s/', user_choice);
else
display('Please select among r, p, or s');
end

채택된 답변

Image Analyst
Image Analyst 2021년 9월 15일
Try it this way:
prompt = 'rock(r),paper(p),or scissors(s)? Make a choice : ';
user_choice = input(prompt, 's');
if ismember(user_choice, {'r', 'p', 's'})
fprintf('Your choice is %s.\n', user_choice);
else
warningMessage = sprintf('You entered %s.\nPlease select among r, p, or s ONLY!', user_choice);
fprintf('%s\n', warningMessage);
uiwait(warndlg(warningMessage));
end
  댓글 수: 3
Image Analyst
Image Analyst 2021년 9월 16일
It basically sees if one item in in a list of other items. See the docuementation for more details.
Lingbai Ren
Lingbai Ren 2021년 9월 24일
The pop out error windows is cool, thanks!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Workspace Variables and MAT-Files에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by