简体   繁体   中英

How do I center a 2d array printed using nested for loops?

How would I go about centering this printed array in the middle of the console?

        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine("0 1 2 3 4 5 6 7");
        Console.ResetColor();
        for (int i = 0; i < 8; i++)
        {
            for (int j = 0; j < 8; j++)
            {
                Console.Write(BoardDisplay[j, i] + " ");
            }
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine(i);
            Console.ResetColor();
        }

I put a few techniques to format console output in this snippet:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace ConsoleApplication9
{
    class Program
    {
        static int[,] BoardDisplay = new int[8, 8] { 
            { 1,2,3,4,5,6,7,8 }
            ,{ 1,2,3,4,5,6,7,8 }
            ,{ 1,2,3,4,5,6,7,8 }
            ,{ 1,2,3,4,5,6,7,8 }
            ,{ 1,2,3,4,5,6,7,8 }
            ,{ 1,2,3,4,5,6,7,8 }
            ,{ 1,2,3,4,5,6,7,8 }
            ,{ 1,2,3,4,5,6,7,8 }
        };

        static void Main(string[] args)
        {
            int space_for_each_cell = 5;
            var width = Console.WindowWidth;
            var height = Console.WindowHeight;

            int left = (width - (8* space_for_each_cell)) / 2;

            Console.ForegroundColor = ConsoleColor.Red;
            Console.CursorLeft = left;
            for (int i = 0; i < 8; i++)
            {
                Console.Write("{0,"+space_for_each_cell+"}", i);
            }
            Console.WriteLine();
            Console.ResetColor();
            for (int i = 0; i < 8; i++)
            {
                Console.CursorLeft = left;
                for (int j = 0; j < 8; j++)
                {
                    Console.Write("{0,"+space_for_each_cell+"}", BoardDisplay[j, i]);
                }
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("{0,"+space_for_each_cell+"}",i);
                Console.ResetColor();
            }
            Console.ReadKey();
        }

    }
}

Apply this concept to suit your need.

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