简体   繁体   中英

Is there any way to save char Array in For loop?

I want to create a simple hangman and I'm stuck :/. Here is simple code what detects all chars in the array. I need some way to save it and then write it. I add the comment in the code for more readability and where I want to save. And at the end i need to write it. Is there anything I could do better in code? I'm a newbie.

public static void Main(string[] args)
{
    char[] array;
    randomWord = "apple".ToCharArray();
    Console.WriteLine(randomWord);
    while (guessing == true) {


    Console.WriteLine();


    userinput = char.Parse(Console.ReadLine());

    for (int i = 0; i < randomWord.Length; i++)
    {
        if (randomWord[i].ToString().Contains(userinput))
        {

        Console.Write(userinput);
        //add to array
         enter code here

        }
        else
        {
        //add to array
         enter code here
        Console.Write("_ ");
        }
    }
    //and here Write whole array
    for(int g = 0; g < array.Lenght; g++){
       Console.Write(array[g]);
    }
}

Use a generic list ( List<T> ) they are more flexible than arrays:

public static void Main(string[] args)
{
    List<char> array = new List<char>();
    randomWord = "apple".ToCharArray();
    Console.WriteLine(randomWord);
    while (guessing == true) {


        Console.WriteLine();


        userinput = char.Parse(Console.ReadLine());

        for (int i = 0; i < randomWord.Length; i++)
        {
            if (randomWord[i].ToString().Contains(userinput))
            {

               Console.Write(userinput);
               //add to array
                array.Add(randomWord[i]);

            }
            else
            {
               //it's not clear what you want to add to here?
               Console.Write("_ ");
            }
        }
        //and here Write whole array
        //use a foreach
        foreach(char c in array ){
           Console.Write(c);
        }
    //your missing a brace
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM