user4298687
user4298687

Reputation:

C# how to add comma in output

I have this code all working good - it only accepts 20 input from user - compare them with the correct answers and finally show the result that which questions are not correct- code is working - shows up the result BUT not separated. its like 156791012 are incorrect. see the attachment.

enter image description here

    static void Main(string[] args)
    {
        char[] studentAnswers = new char[20];            
        char[] answers = new char[] { 'E', 'D', 'D', 'B', 'A', 'C', 'E', 'B', 'D', 'C', 'D', 'A', 'A', 'D', 'E', 'E', 'A', 'E', 'A', 'D' };
        int[] wrongAnswers = new int[20];            
        int correctlyAnswered = 0;
        int falselyAnswered = 0;
        string list = "";


        for (int i = 0; i < studentAnswers.Length; i++)
        {
            studentAnswers[i] = InputOutput_v1.GetValidChar("Question ",i);

            if (studentAnswers[i] == answers[i])
            {
                correctlyAnswered = correctlyAnswered + 1;
            }
            else
            {
                falselyAnswered = falselyAnswered + 1;                    
                wrongAnswers[i] = i + 1;
                list += i + 1;

            }

        }
        if (correctlyAnswered >= 15)
        {
            Console.WriteLine("Passed with {0} correct answers",correctlyAnswered);
        }
        else
        {
            Console.WriteLine("Failed with {0} incorrect answers. Incorrect answers are: {1} ", falselyAnswered, list);
        }
        Console.ReadLine();
    }

Upvotes: 0

Views: 89

Answers (2)

Samvel Petrosov
Samvel Petrosov

Reputation: 7706

Replace

list+= i+1;
Console.WriteLine("Failed with {0} incorrect answers. Incorrect answers are: {1} ", falselyAnswered, list);

to this

list+= i+1 + ",";
Console.WriteLine("Failed with {0} incorrect answers. Incorrect answers are: {1} ", falselyAnswered, list.Remove(list.Length-2));

Upvotes: 0

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186678

Your are looking for string.Join (and Linq):

using System.Linq;

... 

string list = string.Join(", ", studentAnswers
  .Where((answer, i) => answer != InputOutput_v1.GetValidChar("Question ", i))
  .Select((answer, i) => i + 1));

Upvotes: 1

Related Questions