I'm writing a hangman code but i'm having a problem where words that have the same letter multiple times give me a weird output such as if the word would be ARRAY the output would be "A-R---RR--" also if a letter would be guessed wrong the if statement for it would still be displayed and also loop multiple times. How do I fix this?
public string[] words = new string[5] { "ARRAY", "OBJECT", "CLASS", "LOOP", "HUMBER" };
public string[] torture = new string[] { "left arm", "right arm", "left leg", "right leg", "body", "head" };
int i;
public void randomizedWord()
{
Random random = new Random();
int index = random.Next(0, 5);
char[] hidden = new char[words[index].Length];
string word = words[index];
Console.WriteLine(words[index]);
Console.Write("The word is: ");
for (i = 0; i < hidden.Length; i++)
{
Console.Write('-');
hidden[i] = '-';
}
Console.WriteLine();
int lives = 6;
do
{
Console.WriteLine("Guess a letter: ");
char userinput = Console.ReadLine().ToCharArray()[0];
for (int i = 0; i < hidden.Length; i++)
{
if (word[i] == userinput)
{
hidden[i] = userinput;
for (int x = 0; x < hidden.Length; x++)
{
Console.Write(hidden[x]);
}
}
if (userinput != hidden[i])
{
Console.WriteLine("That is not a correct letter");
Console.WriteLine("You lost a " + torture[i]);
lives--;
}
}
Console.WriteLine();
} while (lives != 0);
Console.WriteLine("You guessed right!");
Console.ReadLine();
}
See Question&Answers more detail:os