C#如何在输出中添加逗号

时间:2017-03-28 18:53:24

标签: c#

我的代码一切正常 - 它只接受来自用户的20条输入 - 将它们与正确的答案进行比较,最后显示哪些问题不正确的结果 - 代码正在运行 - 显示结果但未分开。 它像156791012是不正确的。 看附件。

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();
    }

2 个答案:

答案 0 :(得分:1)

您正在寻找string.Join(和 Linq ):

using System.Linq;

... 

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

答案 1 :(得分:0)

替换

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

到这个

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