【问题标题】:C# How can I Validate a User input before it is placed into my array?C#如何在将用户输入放入我的数组之前验证用户输入?
【发布时间】:2020-03-21 17:52:10
【问题描述】:

我对 C# 非常陌生,我想知道如何在将用户输入放入我的数组之前验证用户输入。我正在尝试创建一个控制台应用程序来创建由星星组成的垂直和水平直方图。所以我要求用户输入 1-10 之间的 8 个数字,并将他们的结果作为直方图打印到屏幕上。 我需要 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.
        }
    }
}

【问题讨论】:

  • 请不要将三个问题打包成一个 SO 问题。为了清楚起见,每个都应该单独处理。
  • 就第一点而言,我建议您采用以下两种可能的方法之一:bool isNumber = Int32.TryParse(strNumberChosen, out var num); 可以评估或使用正则表达式评估输入:var reg = new Regex(@"[0-9]"); bool isNumber = reg.IsMatch(strNumberChosen);
  • 嗨,Barns,对不起,我不知道没有提出多个问题。感谢您的回答,我认为您的第一个解决方案对我来说是最好的。但是,我不太明白,我将在我的代码中的哪个位置放置该行?而且我还需要做任何其他事情才能让它工作吗?例如,如果用户输入了一个字母,让他们再试一次,直到他们输入一个数字。非常感谢您的帮助。 :)

标签: c# arrays validation histogram


【解决方案1】:

这是一个使用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&lt;int&gt; 整数而不是数组int[]...我个人的喜好。 我改变了图表的创建方式。我的版本不那么冗长。 我还添加了一个额外的示例,说明如何使用 LINQ 创建图表——总是看起来不错。


如果您有任何问题,请告诉我。

【讨论】:

  • 天哪!非常感谢,巴恩斯。你是个天才。它完美地工作!我将它放入我的代码中,非常感谢您的帮助。现在我需要弄清楚如何垂直显示,哈哈。再次感谢你,我真的很感激你。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-27
  • 1970-01-01
  • 1970-01-01
  • 2020-03-12
  • 2019-06-20
相关资源
最近更新 更多