C# Как я могу проверить ввод пользователя, прежде чем он будет помещен в мой массив? - PullRequest
0 голосов
/ 21 марта 2020

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

1 **** (Number of stars user selected) 
2 ****** (Number of stars user selected)
3 ***** (Number of stars user selected)
4 * etc.

Буду очень признателен за любую помощь! Огромное спасибо заранее. :) Вот что у меня есть:

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.
        }
    }
}

1 Ответ

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

Вот пример кода, который будет использовать метод int.TryParse() для оценки введенных данных.

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

    private static void CreateHorizontalHistogram()
    {
        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);

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

        Console.WriteLine("Your 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)));
    }



ПРИМЕЧАНИЕ:
Я использовал List<int> целых чисел вместо массива int[] ... мои личные предпочтения. Я изменил способ создания диаграммы. Моя версия немного менее многословна. Я также добавил дополнительный пример того, как вы можете создать диаграмму, используя LINQ - всегда выглядит хорошо.


Пожалуйста, дайте мне знать, если у вас есть какие-либо вопросы.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...