user9911150
user9911150

Reputation:

What am I doing wrong when using string.join in my code?

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"

Upvotes: 0

Views: 85

Answers (1)

Sumit raj
Sumit raj

Reputation: 831

Just replace

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

with

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

Unless you really need to dequeue.

Upvotes: 3

Related Questions