简体   繁体   English

仅将数字添加到数组C#验证数字

[英]Add numbers to array c# validating numbers only

I'm taking a C# class this semester and it has been quite fun so far. 这个学期我要上一门C#课,到目前为止,它非常有趣。 I have an assignment where I need to do several things with an array: add numbers in the array, see the numbers entered in the array, find a number in the array, sort the numbers in the array, create statistics based on the array numbers, and finally exit the application. 我有一个作业,需要在数组上做几件事:在数组中添加数字,查看在数组中输入的数字,在数组中查找数字,对数组中的数字进行排序,基于数组数字创建统计信息,最后退出应用程序。

So far I have been having a little bit of an issue with adding numbers to the array while making sure that the data entered is only numbers. 到目前为止,我一直在向数组添加数字时遇到一点问题,同时确保输入的数据仅为数字。 I think I am about to figure it out, but help is always appreciated. 我想我会解决这个问题,但总是能得到帮助。 And, does my findData() method look ok? 而且,我的findData()方法看起来还可以吗?

Thank you again for your time in reading this question! 再次感谢您抽出宝贵时间阅读此问题!

class Program
{

    static char myChoice = Console.ReadKey().KeyChar;
    static double[] myArray = new double[100];
    static void Main(string[] args)
    {



        while (true)
        {

            Console.WriteLine("Welcome to Lab 2");
            Console.WriteLine();
            Console.WriteLine("Main Menu");
            Console.WriteLine("1- Add new data");
            Console.WriteLine("2- See all data");
            Console.WriteLine("3- Find a number");
            Console.WriteLine("4- Sort the data");
            Console.WriteLine("5- Create statistics");
            Console.WriteLine("6- Exit Program");


            switch (myChoice)
            {
                case '1':
                    Console.WriteLine("1- Add new data");
                    addData();
                    break;

                case '2':
                    Console.WriteLine("2- See all data");
                    seeData();
                    break;

                case '3':
                    Console.WriteLine("3- Find a number");
                    findData();
                    break;

                case '4':
                    Console.WriteLine("4- Sort the data");
                    sortData();
                    break;

                case '5':
                    Console.WriteLine("5- Create statistics");
                    createData();
                    break;

                case '6':
                    Console.WriteLine();
                    exitProgram();
                    break;

            }
        }
    }

    //This method will add numbers to the array
    public static void addData()
    {
        bool isNumber = false;
        double number;
        double temp;

        for (int i = 0; i < myArray.Length; i++)
        {
            Console.WriteLine("Enter a number you would like to add");

            myArray[i] = Convert.ToDouble(Console.ReadLine());
            temp = myArray[i];

            if (!Double.TryParse(temp, out number))
            {
                Console.WriteLine("Invalid input. Please enter a valid number")
            }

            else
            {

            }
        }
    }

    //This method will see the numbers entered in the array
    public static void seeData()
    {
        foreach (var item in myArray)
        {
            Console.WriteLine(item.ToString());
        }
    }

    //This method will find a specific number within the array and check if it has already been entered
    public static void findData()
    {

        Console.WriteLine("Find a number");
        string myChoice = Console.ReadLine();
        double number;
        bool isNumber = Double.TryParse(myChoice, out number);

        {

        }

    }

    //This method will sort the array ascending to descending
    public static void sortData()
    {
        Console.WriteLine("The array has been sorted in ascending order");
        Array.Sort(myArray);
        Console.WriteLine("The array has been sorted in descending order");
        Array.Reverse(myArray);
    }

    //This method will create statistics based on the numbers in the array
    public static void createData()
    {

        //Sum
        double sum = myArray.Sum();
        Console.WriteLine("The total sum of the array is: " + sum);

        //Average
        double average = sum / myArray.Length;
        Console.WriteLine("The average number of the array is: " + average);

        //Maximum
        double maximum = myArray.Max();
        Console.WriteLine("The maximum value in the array is: " + maximum);

        //Minimum
        double minimum = myArray.Min();
        Console.WriteLine("The minimum value in the array is: " + minimum);

        //Mean
        double mean = sum / myArray.Length;
        Console.WriteLine("The mean average of the array is: " + mean);
    }

    //This method will exit the program
    public static void exitProgram()
    {
        Environment.Exit(0);
    }
}

} }

does my findData() method look ok? 我的findData()方法看起来还可以吗?

Your findData() method does acutally nothing. 您的findData()方法根本不执行任何操作。

Here is one approach 这是一种方法

public static void findData()
{
    Console.WriteLine("Find a number");
    string myChoice = Console.ReadLine();
    double number = -1;  

    if(!Double.TryParse(myChoice, out number))
    {
        Console.WriteLine("Invalid number");
    }
    else if (Array.IndexOf<double>(myArray, number) == -1)
    {
        Console.WriteLine("Number does not exist");
    }
    else
    {
        Console.WriteLine("Number does exist");
    }
}

This should solve your add problem 这应该解决您的添加问题

  public static void addData()
            {
                for (int i = 0; i < myArray.Length; i++)
                {
                    bool success = false;
                    while (!success)
                    {
                        Console.WriteLine("Enter a number you would like to add");
                        string input = Console.ReadLine();
                        double number;
                        if (Double.TryParse(input, out number))
                        {
                            success = true;
                            myArray[i] = number;
                        }

                        else
                        {
                            Console.WriteLine("Invalid input. Please enter a valid number")
                        }
                    }
                }
            }

Your addData method doesn't make much sense: you first insert a double value into array and then you check if that value is a double (and it certainly is, because the array is of type double and can contain values only of that type). 您的addData方法没有多大意义:首先将一个double值插入到数组中,然后检查该值是否为double(当然是,因为数组的类型为double,并且只能包含该类型的值) 。

Also, the Convert.ToDouble may throw exception if the user input is not valid. 另外,如果用户输入无效,则Convert.ToDouble可能会引发异常。 But I see you get the point of using Double.TryParse method, which returns true if the string (first parameter) is a valid number. 但是我知道您可以使用Double.TryParse方法,如果字符串(第一个参数)是有效数字,则该方法返回true。 So your addData method should look something like this: 因此,您的addData方法应如下所示:

//This method will add numbers to the array
public static void addData()
{
    double number;

    for (int i = 0; i < myArray.Length; i++)
    {
        Console.WriteLine("Enter a number you would like to add");
        // read user input
        string input = Console.ReadLine();
        // condition is true if user input is a number
        if (double.TryParse(input, out number))
            myArray[i] = number;
        else
            Console.WriteLine("Invalid input. Please enter a valid number");
    }
}

To find a number in your array you can use LINQ Contains extension method which does exacly that: it returns true if array contains element, otherwise false: 要在数组中查找数字,可以使用LINQ Contains扩展方法,该方法确实做到:如果数组包含element,则返回true,否则返回false:

//This method will find a specific number within the array and check if it has already been entered
public static void findData()
{
    double number;
    Console.WriteLine("Find a number");
    string input = Console.ReadLine();
    // we use the same logic here as in the addData method to make sure the user input is a number
    if (!double.TryParse(input, out number))
    {
        bool found = myArray.Contains(number);
        if (found)
            Console.WriteLine("Array has number {0}", number);
        else
            Console.WriteLine("Array doesn't have number {0}", number);
    }
    else
    {
        Console.WriteLine("Invalid input. Please enter a valid number");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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