简体   繁体   中英

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

I am new to serious programming with a bit of experience in elementary Pascal. I am currently trying to figure out how to create a hollow square with user defined parameters in C#. I've managed to get 3 out of the 4 sides but I am out of ideas on how to manage the fourth one. This is my code so far:

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

I would also be happy if you can suggest an easier/better/more optimised solution if you think mine is bad. Thank you very much for your time!

In your while (counterH < height) loop you should loop through your width-Value and place some spaces. At the End you can place a Pipe | again.

Use Console.Write() and not Console.WriteLine() at this position, because you dont want a LineFeed / CarriageReturn after your first Pipe.

Example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM