Borivoj Brankov
Borivoj Brankov

Reputation: 13

List to show all the numbers I guessed

I'm having trouble to show all the numbers I typed in console. I need to create list that will show all the numbers I guessed.

for (int i = 0; i < 100000; i++)
{
    z++; 
    Console.Write("\nGuess the number I imagined: ");

    int c = Convert.ToInt32(Console.ReadLine()); // all of numbers that I type should appear.

    if (b == c)
    {

        Console.WriteLine("\n Congratulations you guessed in {0} attempts. :)",z); // this is just showing how many attempts I had.

        List<int> Attemptsnums= new List<int>();

        Attemptsnums.Add(c); // here I've put c but It only shows last number I entered, I need all of them in line.

        foreach (var element in Attemptsnums)
        {
            Console.WriteLine("Numbers: {0}", element);
        }

        break;
    }
}

Upvotes: 0

Views: 88

Answers (3)

sr28
sr28

Reputation: 5106

There's 1 main thing wrong with what you're currently doing. In your 'for loop' you are always creating 'Attemptsnums' as a new list, which means it will always be emptied before you add 'c'. Declare the list before the 'for loop' and it will add 'c' to it every time.

I'm also assuming that you're running the for loop up to 100,000 for some reason. However, what's interesting is you're never using the variable 'i' but are then incrementing 'z' by 1 each time. What does 'z' start at? If it starts at 0 you could just remove 'z' in the for loop and where you're displaying 'z' you could just display 'i'.

Upvotes: 1

Christophe Chenel
Christophe Chenel

Reputation: 1921

try this

List<int> Attemptsnums= new List<int>();   

for (int i = 0; i < 100000; i++)
{
z++; 
Console.Write("\nGuess the number I imagined: ");

int c = Convert.ToInt32(Console.ReadLine()); // all of numbers that I type should appear.

if (b == c)
{

    Console.WriteLine("\n Congratulations you guessed in {0} attempts. :)",z); // this is just showing how many attempts I had.



    Attemptsnums.Add(c); // here I've put c but It only shows last number I entered, I need all of them in line.

    foreach (var element in Attemptsnums)
    {
        Console.WriteLine("Numbers: {0}", element);
    }

    break;
 }
}

Upvotes: 0

Antoine V
Antoine V

Reputation: 7204

Move :

List<int> Attemptsnums= new List<int>(); outside the loop

Attemptsnums.Add(c); before if

Upvotes: 0

Related Questions