0

I have the code below, which I need to separate the result with ", ". I have so far used different methods because whenever I try to use String.Join, it doesn't work as expected. What am I doing wrong?

Code:

using System;
using System.Collections.Generic;
using System.Linq;

namespace _5._PrintEvenNumbers
{
    class Program
    {
        public static void Main()
        {
            var input = Console.ReadLine().Split().Select(int.Parse).ToList();

            var numbers = new Queue<int>();

            for (int i = 0; i < input.Count(); i++)
            {
                if (input[i] % 2 == 0)
                {
                    numbers.Enqueue(input[i]);
                }
            }

            while (numbers.Any())
            {
                Console.Write(string.Join(", ", numbers.Dequeue()));
            }
        }
    }
}

Expected result should be "2, 4, 6" for example. Currently it prints it "246"

3
  • Sorry. I had the code updated a bit so it prints every dequeued number. I am typing in(with the current code), 2 4 6 OR 246 and both are resulting in 246, instead of 2, 4, 6 Commented Jan 19, 2019 at 17:46
  • 3
    Numbers.Dequeue takes only one number from queue, so string.Join does not have anything to join. Commented Jan 19, 2019 at 17:51
  • 1
    You should not put it in loop, just pass a collection to it. Commented Jan 19, 2019 at 17:52

1 Answer 1

3

Just replace

while (numbers.Any())
{
   Console.Write(string.Join(", ", numbers.Dequeue()));
}

with

Console.Write(string.Join(", ", numbers));

Unless you really need to dequeue.

Sign up to request clarification or add additional context in comments.

2 Comments

UPDATE: now that you've updated the answer, it actually works. Thanks!
Sorry it was because i blindly copied the line.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.