MATLAB Answers

How can I keep asking the user for correct input even after they press enter?

56 views (last 30 days)
JkBlack on 29 Jan 2021
Edited: JkBlack on 2 Feb 2021
I want my statement to continue to be prompted until correct input is given.
Prompt the user to write "ready" or "Ready" and keep prompting the user until they do so, and if they just pressed enter, a statement shows up asking them to "Please type "Ready"". I am a little lost as to how to do that using while(1) loop. I have this so far...
while (1)
Ready= input('When you are ready to play please type "Ready": ','s');
if Ready== 'ready' | Ready== 'Ready'
Please help
Thank you in advance.

Accepted Answer

Adam Danz
Adam Danz on 29 Jan 2021
Edited: Adam Danz on 29 Jan 2021
Most of the time case sensitivity shouldn't be a constraint in these types of queries. The demo below accepts any form of "ready" (READY, ready, Ready, reaDY, etc).
response = '';
while ~strcmpi(response,'ready')
response = input('When you are ready to play please type "Ready": ','s');
If you truly only want to accept Ready and ready, use this condition instead,
while ~any(strcmp(response, {'Ready','ready'}))
Another form that gives the user feedback on their error,
instructions = 'When you are ready to play please type "Ready": ';
baseInstructions = instructions;
response = '';
while ~strcmpi(response,'ready')
response = input(instructions,'s');
instructions = sprintf('%s, (you typed "%s") ',baseInstructions, response);
Another idea since this is a binary task (the user types the correct word or they do not), why not use a question or message box?
qdh = questdlg('When you are ready to play, please press go!', 'Game', 'Go!','Go!');
You could also add a "Cancel" option.
JkBlack on 2 Feb 2021
Your help is very much appreciated! Thank you for pointing this out and sharing this information, will keep it in my mind.
Best Regards,

Sign in to comment.

More Answers (1)

per isakson
per isakson on 29 Jan 2021
strcmpi( Ready, 'ready' )
instead of
Ready== 'ready' | Ready== 'Ready'
Don't use == in combination with character arrays to compare words. It compares character by character.
>> 'abc'=='a*c'
ans =
1×3 logical array
1 0 1
in contrary to strings
>> "abc"=="a*c"
ans =
JkBlack on 29 Jan 2021
Yes this worked! Thank you very much for sharing this information!
Best Regards,

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!