如何在 C# 控制台应用程序中创建一个空心方块(用户参数)?

How to create a hollow square (user parameters) in C# console applications?

我是正式编程的新手,对基本的 Pascal 有一点经验。我目前正在尝试弄清楚如何在 C# 中使用用户定义的参数创建一个空心正方形。我已经设法从 4 个方面中获得 3 个,但我不知道如何管理第四个方面。到目前为止,这是我的代码:

class Program
{
    static void Main(string[] args)
    {
        int height;
        int width;
        int counterH = 0;
        int counterW2 = 0;
        int counterW1 = 0;
        Console.WriteLine("Please input the sizes of the square!");
        Console.WriteLine("Please input the height of the square.");
        height = int.Parse(Console.ReadLine());
        Console.WriteLine("Please input the width of the square");
        width = int.Parse(Console.ReadLine());
        while (counterW1 < width)
        {
            Console.Write("--");
            counterW1++;}
        Console.WriteLine();
            while (counterH < height)
            {
                Console.WriteLine("|");
                counterH++;
            }
            while (counterW2 < width)
            {
                Console.Write("--");
                counterW2++;
            }
            Console.ReadLine();
        }
    }

如果您认为我的方法不好,可以提出 easier/better/more 优化的解决方案,我也很高兴。非常感谢您的宝贵时间!

在您的 while (counterH < height) 循环中,您应该遍历宽度值并放置一些空格。在最后你可以放置一个 Pipe |再次.

在此位置使用 Console.Write() 而不是 Console.WriteLine(),因为您不希望在第一个管道后出现 LineFeed / CarriageReturn。

示例:

    while (counterH < height)
    {
        Console.Write("|");
        int counterW3 = 0;
        while (counterW3 < width)
        {
            Console.Write(" ");
            counterW3++;
        }
        Console.Write("|" + System.Environment.NewLine);
        counterH++;
    }