Dealing with wrong input

How do I avoid this error? I would like for users, if they enter a string instead of number to told "Those are not the instructions, please try again"
Screenshot 2019-09-03 at 12.40.08.png

4 comentarios

Nicolas B.
Nicolas B. el 3 de Sept. de 2019
Can you provide your example code?
Lars Morsink
Lars Morsink el 3 de Sept. de 2019
Screenshot 2019-09-03 at 20.34.16.png
Rik
Rik el 3 de Sept. de 2019
Please post your code as code, not as a screenshot. You can find an explanation of the layout tools here.
Lars Morsink
Lars Morsink el 3 de Sept. de 2019
clc,
clear
Secret_Number = randi(100);
Attempts = 0;
Max_Attempts = 10;
Guess = -1; % The variable needs to be established to avoid an error in the 'while...end' loop and -1 guarantees that it is not equal to the secret number
disp (' ')
disp ('Instructions: Guess a number between 1 and 100. You have 10 guesses and a hint after each guess. Good luck!')
while (Attempts < Max_Attempts) && (Secret_Number ~= Guess)
disp (' ')
Guess = input('Please enter your guess: ');
Attempts = Attempts + 1;
if Secret_Number == Guess
disp (' ')
disp ('Congratulations! You guessed the secret number!')
Attempts
elseif (Guess > Secret_Number) && (Attempts < Max_Attempts);
disp (' ')
disp ('Hint: Guess lower')
else
disp (' ')
disp ('Hint: Guess higher')
end
end
if Attempts == Max_Attempts & (Secret_Number ~= Guess);
disp (' ')
disp ('Game Over! You ran out of guesses. Please play again.')
Secret_Number
end

Iniciar sesión para comentar.

Respuestas (2)

Stephen23
Stephen23 el 3 de Sept. de 2019
Editada: Stephen23 el 3 de Sept. de 2019

0 votos

str = '';
num = NaN;
while isnan(num)
num = str2double(input([str,'Enter a number: '],'s'));
str = 'Please try again! ';
end
And tested:
Enter a number: hello
Please try again! Enter a number: world
Please try again! Enter a number: 42
Nicolas B.
Nicolas B. el 3 de Sept. de 2019
Editada: Nicolas B. el 3 de Sept. de 2019

0 votos

Okay, then I would use the exception catching method:
str = '';
num = NaN;
while isnan(num)
try
num = input('Please enter your guess: ');
catch
disp('You must give a valid number!');
num = NaN;
end
end

1 comentario

Rik
Rik el 3 de Sept. de 2019
That's also possible, although I think it would make slightly more sense to use Stephen's method, because then it also isn't possible to provide a variable name.
If you define a=9; before your loop, you can enter a in the prompt and it will pass the test. With Stephen's code, that is not possible.

Iniciar sesión para comentar.

Categorías

Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

el 3 de Sept. de 2019

Comentada:

el 3 de Sept. de 2019

Community Treasure Hunt

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

Start Hunting!

Translated by