C# Как отобразить вертикальную гистограмму? - PullRequest
0 голосов
/ 22 марта 2020

Я очень плохо знаком с C# и пытаюсь создать консольное приложение для создания вертикальной и горизонтальной гистограммы, состоящей из звезд. Поэтому я прошу пользователя ввести 8 чисел от 1 до 10 и вывести их результаты на экран в виде гистограммы. Мне нужна помощь с отображением гистограммы по вертикали, я сделал горизонтальную и не могу понять, как сделать ее вертикальной. Вот что я получил до сих пор: очень признателен за любую помощь. Заранее спасибо. Я бы хотел, чтобы это выглядело примерно так:

*
*  *
*  *  *
*  *  *  *
*  *  *  *  *(Height of row depends on numbers user enters.)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Exercise_3A
{
    class Program
    {
        static void Main(string[] args)
        {
            clsMainMenu MainMenu = new clsMainMenu();
            ConsoleKeyInfo ConsoleKeyPressed;

            do
            {
                MainMenu.DisplayMenu();
                ConsoleKeyPressed = Console.ReadKey(false);
                Console.WriteLine();
                switch (ConsoleKeyPressed.KeyChar.ToString())
                {
                    case "1":
                        clsHistogram Histogram = new clsHistogram();
                        Histogram.CreateHorizontalHistogram();
                        break;
                    case "2":
                        clsHistogram HistogramV = new clsHistogram();
                        HistogramV.CreateVerticalHistogram();
                        break;
                }
            } while (ConsoleKeyPressed.Key != ConsoleKey.Escape);

        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Exercise_3A
{
    class clsMainMenu
    {
        public void DisplayMenu()
        {
            Console.WriteLine("1. Create a Horizontal Histogram.");
            Console.WriteLine("2. Create a Vertical Histogram.");
            Console.WriteLine("Press Esc to exit the Program.");
            Console.WriteLine("..................................");
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Exercise_3A
{
    class clsHistogram
    {
        string strNumberChosen = "";

        public void CreateHorizontalHistogram()
        {
            Console.WriteLine("Please enter a number between 1 and 10:");

            int[] intHistogramArray = new int[8];

            for (int intCounter = 0; intCounter < 8; intCounter++)
            {
                Console.WriteLine("Enter number " + (intCounter + 1) + " :");
                strNumberChosen = Console.ReadLine(); // Need Data Validation Here.             
            } // Populating Array.

            Console.WriteLine("Your Histogram looks like this: ");
            for (int intcounter = 0; intcounter < 8; intcounter++)
            {
                int intStarPlot = intHistogramArray[intcounter];
                while (intStarPlot > 0)
                {
                    Console.Write(" *");
                    intStarPlot -= 1;
                }
                Console.WriteLine();
            } // Display a Horizontal Array.
        }


        public void CreateVerticalHistogram()
        {
            Console.WriteLine("Please enter a number between 1 and 10:");

            int[] intHistogramArray = new int[8];

            for (int intCounter = 0; intCounter < 8; intCounter++)
            {
                Console.WriteLine("Enter number " + (intCounter + 1) + " :");
                strNumberChosen = Console.ReadLine(); // Need Data Validation Here.
            } // Populating Array.

            Console.WriteLine("Your Histogram looks like this: ");
            for (int intcounter = 0; intcounter < 8; intcounter++)
            {
                int intStarPlot = intHistogramArray[intcounter];
                while (intStarPlot > 0)
                {
                    Console.Write(" * \n");
                    intStarPlot -= 1;
                }
                Console.WriteLine();
            } // Display a Vertical Array.
        }
    }
}

Ответы [ 2 ]

1 голос
/ 23 марта 2020

Вот небольшая тестовая программа, которая поможет вам начать создание вертикальной гистограммы. Обратите внимание, что я объединил последнее решение, которое я предоставил для горизонтальной гистограммы, и сделал код более универсально применимым:

private static readonly char star = '*';
private static readonly uint minValue = 1;
private static readonly int maxValue = 10;

static void Main(string[] args)
{
     var list = GetHistorgramData();
     CreateHorizontalHistogram(list);
     CreateVerticalHistogram(list);
}

private static void CreateHorizontalHistogram(List<int> list)
{
    Console.WriteLine("Your Horizontal Histogram looks like this: ");
    //foreach(var value in list)
    //{
    //    Console.WriteLine(string.Empty.PadRight(value, star));
    //}

    //Console.WriteLine("Or like this with LINQ");
    list.ForEach(n => Console.WriteLine(string.Empty.PadRight(n, star)));
}



private static void CreateVerticalHistogram(List<int> list)
{
    Console.WriteLine("Your Vertical Histogram looks like this: ");
    for(int i = 0; i < maxValue + 1; i++)
    {
        var displayLine = string.Empty;
        foreach(int x in list)
        {
            displayLine += ((x + i) - maxValue) > 0 ? star.ToString() : " ";
        }
        Console.WriteLine(displayLine);
    }
}



private static List<int> GetHistorgramData()
{
    var limits = "a number between " + minValue + " and " + maxValue + ": ";
    Console.WriteLine("Please enter " + limits);

    var list = new List<int>();

    do
    {
        var message = string.Empty;
        bool isNumber = false;
        bool isRightSize = false;
        int output;

        do
        {
            var input = Console.ReadLine();      
            isNumber = int.TryParse(input, out output);
            if(isNumber)
            {
                isRightSize = minValue <= output && output <= maxValue;
                message = isRightSize ? "That will do: " : "Try again - value is not " + limits + output;
            }
            else
            {
                message = "Try again - " + input + " is not a Number";
            }
            Console.WriteLine(message);
        }while(!isNumber || !isRightSize);

        list.Add(output);
        Console.WriteLine("Entered number at position" + list.Count + " : " + output);
    }while(list.Count < 8);

    return list;
}

Вертикальные результаты:

    *    
   **    
   **    
  ****   
  ****   
 ******  
 ******* 
********
********

для ввода:

Please enter a number between 1 and 10: 
2
Entered number at position1 : 2
4
Entered number at position2 : 4
6
Entered number at position3 : 6
8
Entered number at position4 : 8
9
Entered number at position5 : 9
6
Entered number at position6 : 6
4
Entered number at position7 : 4
3
Entered number at position8 : 3


ПРИМЕЧАНИЕ : Я предлагаю вам использовать метод GetHistorgramData() для вертикальной и горизонтальной. Вы можете решить, будете ли вы sh использовать LINQ для горизонтальной гистограммы или версию foreach l oop. Я думаю, что мог бы сделать LINQ версию для вертикальной гистограммы, но я чувствовал, что это может показаться странным. Возможно, вы захотите немного изменить гистограмму, но имейте в виду, что ширина пробела "" отличается от ширины звезды "*". Пожалуйста, дай мне знать, если возникнут какие-либо вопросы.

1 голос
/ 22 марта 2020
  int currentValue = 1;
            bool allDone = false;
            Console.WriteLine("Your Histogram looks like this: ");

            while (!(allDone))
            {
                int x = 0;
                for (int intcounter = 0; intcounter < 8; intcounter++)
                {
                    if (intHistogramArray[intcounter] >= currentValue)
                    {
                        Console.Write(" * ");
                    }
                    else
                    {
                        Console.Write("   ");
                        x = x + 1;
                    }
                }
                if (x>=8) { allDone = true; }
                currentValue = currentValue + 1;
                Console.WriteLine();
            }

output:

Your Histogram looks like this:
 *  *  *  *  *  *  *  *
    *  *  *  *  *  *  *
       *  *  *  *  *  *
          *  *  *  *  *
             *  *  *  *
                *  *  *
                   *  *
                      *

Если вы хотите, чтобы они были выровнены по нижнему краю , вам нужно внести некоторые небольшие изменения, это просто, чтобы дать вам представление о как начать.

...