There is a program that should display the word, where the letters are replaced by the '_' character and the user one letter guesses this word. The problem is that the program displays only 1 letter and is also replaced only one at a time and after entering a word, the letters do not stop working. Help me find a bug.

string[] slovo = new string [] {"algoritm"}; char[] guess = new char[slovo.Length]; for (int p = 0; p < slovo.Length; p++) guess[p] = '_'; while(true) { Console.WriteLine(guess); char bukva = Convert.ToChar(Console.ReadLine()); for (int j=0; j < slovo.Length; j++) { if (slovo[j].Contains(bukva)) guess[j] = bukva; else Console.WriteLine("Takoj bukvi net!"); } } 
  • 2
    Just use the debugger - Andrew NOP
  • one
    string[] slovo = new string [] {"algoritm"}; - why array? accordingly for (int p = 0; p < slovo.Length; p++) - cycle from 0 to 0 - slippyk

2 answers 2

 using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Text; namespace Rextester { public class Program { public static void Main(string[] args) { string slovo = "algoritm"; // Ваше слово string guess = "________"; // Ваш ответ StringBuilder sb = new StringBuilder(guess); // Для изменения букв по индексу while(true) { Console.WriteLine(guess); // Выводим ваш ответ char bukva = Convert.ToChar(Console.ReadLine()); // Считываем букву for (int i = 0; i < slovo.Length; i++) // Лучше использовать массив, т.к. Contains показывает лишь 1 вхождение, а таких букв в слове может быть больше { if (slovo[i] == bukva) { sb[i] = bukva; // Если есть совпадение, заменяем '_' на эту букву } guess = sb.ToString(); // Приводим наш объект StringBuilder к типу String для WriteLine при следующей итерации } } } } } 

I hope you add the exit condition from the program yourself.
Also do not forget to insert using System.Text to work with StringBuilder .

UPDATE

If you decide to use the guess variable name, do the same for other names. Note use word instead of slovo . It is not a good practice to give such different names.

      string slovo = "algoritm"; char[] guess = new char[slovo.Length]; for (int p = 0; p < guess.Length; p++) guess[p] = '_'; while (true) { Console.WriteLine(guess); string bukva2 = Console.ReadLine(); char bukva = ' '; if (bukva2.Length == 1) bukva = Convert.ToChar(bukva2); bool EstBukva = false; for (int j = 0; j < slovo.Length; j++) { if (slovo[j] == bukva) { guess[j] = bukva; EstBukva = true; } } if (!EstBukva) { Console.WriteLine("Takoj bukvi net!"); Console.ReadKey(true); } Console.Clear(); } 

    I would do that

    • What does the condition if (! EstBukva) mean? Is this condition for the case if the value remains false? - higque
    • yes, precisely for this - GigSter