If statement with == not working with vector
3 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
So I'm making a code that's basically Hangman where the user has to guess the letters in a word that's already been decided. I did that by making each word into a vector.
The if/else statement shown below is where, if the letter the user enters matches a letter in the word, it prints "correct" but if it doesn't, it prints "incorrect". My issue is that even if the user's guess matches one of the letter, (and it prints "correct"), it also prints incorrect for every other letter.
if guess==word(k)
disp ('Correct!')
else
disp ('Incorrect')
end
I tried writing it as two seperate if statements but that didn't change anything.
if guess==word(k)
disp ('Correct!')
end
if all(guess~=word(k))
disp ('Incorrect')
end
I also tried the two if statemnts with break at the end of each but that jsut made it print incorrect every time.
Anyone have any idea how to fix this? I'd really appreciate it!
EDIT:
I've added my code as a whole so you can see what I'm trying to do, in case that makes things clearer:
disp ('Lets Play Hangman (the theme is colours)')
disp (' ')
r=randi([1,4],1);
if r==1
word='RED';
elseif r==2
word='ORANGE';
elseif r==3
word='YELLOW';
elseif r==4
word='GREEN';
end
len_word= length(word);
fprintf ('Your letter is %d letters long \n', len_word)
attempts_left=9;
for k=1:len_word
shadow_array(k) = '*';
end
for max_guesses=[1:1:9]
guess=input('Enter a letter: ', 's');
guess=upper(guess);
for k=[1:1:len_word]
word(k);
% PROBLEM AREA
if guess==word(k)
disp ('Correct!')
shadow_array(k)=num2str(word(k));
else
disp ('Incorrect')
attempts_left=attempts_left-1
end
% issue is that it else runs for every letter that ~=k (even if one letter is correct)
end
disp (shadow_array)
if all (shadow_array~='*')
disp ('\nYOU WON!\n')
break
end
end
disp ('GAME OVER')
0 Commenti
Risposte (1)
Star Strider
il 27 Ago 2020
Modificato: Star Strider
il 27 Ago 2020
2 Commenti
Star Strider
il 28 Ago 2020
I do not see that in the other code you posted.
It should not jump to the end of the code. It should instead continue in whatever loop you put it, so only when the conditions for the loop are satisfied should the loop terminate and go to the end of the code. (It would seem that it has to be in the ‘max_guesses’ loop somewhere. I leave it to you to determine where that is.)
Also, experiment with something along the lines of:
if any(it_is_there)
since depending on the word, there could be more than one match, for example ‘YELLOW’ and ‘GREEN’. It is also not necessary to test that it is equal to 1, simply that it is true, and the any function will detect that.
Vedere anche
Categorie
Scopri di più su Characters and Strings in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!