如何使用Console.write编写数字组

本文关键字:数字 write 何使用 Console | 更新日期: 2023-09-27 18:26:14

我是C#的新手(还有Stack Overflow,请原谅我在这里的礼仪不好),我正在控制台应用程序中编写游戏Mastermind。我试图在游戏结束时显示用户的猜测列表,我知道使用Console.WriteLine();只会给我30多行数字,这些数字不会告诉用户任何信息。

如何更改我的代码,使程序一次在一组中显示4个数字?例如:

1234

1234

1234

//Store numbers in a history list
ArrayList guesses = new ArrayList(); //This is the ArrayList
Console.WriteLine("Please enter your first guess.");
guess1 = Convert.ToInt32(Console.ReadLine());
guesses.Add(guess1);
foreach (int i in guesses)
{
    Console.Write(i);
}

如何使用Console.write编写数字组

我假设字节数组的每个元素都是一个数字(0-9)。如果这个假设无效,请告诉我,我会修改代码:)

Action<IEnumerable<int>> dump = null;
dump = items =>
            {
                if(items.Any())
                {
                  var head = String.Join("", items.Take(4));
                  Console.WriteLine(head);
                  var tail = items.Skip(4);
                  dump(tail);
                }
            };
dump(guesses);

看起来你已经完成了大部分工作,你有一个控制台写,可以在没有换行符的情况下把它们全部写出来。接下来添加一个整数count并将其设置为零。在foreach循环中将其递增一。则CCD_ 2对于四的倍数的所有计数都将为真。这意味着你可以在那里粘贴一个if块和一条写线,给你四个人一组。

List<int> endResult = new List<int>();
StringBuilder tempSb = new StringBuilder();
for(int i=0; i < groups.Count; i++)
{
    if(i % 4 == 0) {
        endResult.Add(int.Parse(sb.ToString()));
        tempSb.Clear(); // remove what was already added
    }
    tempSb.Append(group[i]);
}
// check to make sure there aren't any stragglers left in
// the StringBuilder. Would happen if the count of groups is not a multiple of 4
if(groups.Count % 4 != 0) {
    groups.Add(int.Parse(sb.ToString()));
}

这将给你一个4位整数的列表,并确保你不会丢失任何整数,如果你的组列表中的整数不是4的倍数。请注意,我将根据您提供的内容继续,因此组是int的ArrayList。

这是我很快拼凑起来的一些东西:

更新:

ArrayList guesses = new ArrayList(); //This is the ArrayList
    // Four or more
    guesses.Add(1); guesses.Add(2);
    guesses.Add(3);guesses.Add(4);
    guesses.Add(5); guesses.Add(6); guesses.Add(7);guesses.Add(8); guesses.Add(9);
    //Uncomment-Me for less than four inputs
    //guesses.Add(1); guesses.Add(2);
    int position = 0;
    if (guesses.Count < 4)
    {
        for (int y = 0; y < guesses.Count; y++)
        {
            Console.Out.Write(guesses[y]);
        }
    }
    else
    {
        for (int i = 1; i <= guesses.Count; i++)
        {
            if (i%4 == 0)
            {
                Console.Out.WriteLine(string.Format("{0}{1}{2}{3}", guesses[i - 4], guesses[i - 3],
                                                    guesses[i - 2], guesses[i - 1]));
                position = i;
            }
            else
            {
                if (i == guesses.Count)
                {
                    for (int j = position; j < i; j++)
                    {
                        Console.Out.Write(guesses[j]);
                    }
                }
            }
        }
    }