I have searched this site for similar questions and the ones I've found don't work for me. I apologize for asking if the answer is somewhere and I haven't been able to find it. Please let me know if I am doing something wrong by asking this.
I am making hangman in C#. What I've done is make it so that the program picks a random string from an array, makes an array of the guessed letters (which it initially fills with '_' for as long as the word is). It then is supposed to get a user's input for a letter, see if that letter is in the word, and if it is, add that letter to the guessed letters array. I am stuck at this part:
if (gameWord.Contains(guessedLetter))
{
//for every character in gameWord
for (int x = 0; x < gameWord.Length; x++)
{
//if the character at the 'x' position in gameWord is equal to the guessed letter
if (gameWord[x] == guessedLetter)
{
//guessString at that x position is equal to the guessed letter
guessString[x] = guessedLetter;
}
}
}
At "if (gameWord[x] == guessedLetter)
" I am getting the error shown in the title.
gameWord is a string chosen from an array of strings, and guessedLetter is a string inputted by the user with Console.ReadLine();
.
The char type is a primitive, like int, so we use == and != to compare chars.
The conditional logical OR operator || , also known as the "short-circuiting" logical OR operator, computes the logical OR of its operands. The result of x || y is true if either x or y evaluates to true . Otherwise, the result is false . If x evaluates to true , y is not evaluated.
If guessedLetter
is a string
, then you need to change one type to the other. You could easily just get the first character of guessedLetter
:
if (gameWord[x] == guessedLetter[0])
or call ToString()
on gameWord[x]
as the other answer suggests.
However, you are about to run into a much bigger problem. [] is a readonly operation (MSDN) since strings are immutable, so your next line (the assignment) will fail.
To do that, you'll need a StringBuilder
:
StringBuilder sb = new StringBuilder(gameWord);
sb[index] = guessedLetter[0];
gameWord = sb.ToString();
Credit to Replacing a char at a given index in string? for that code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With