C# user input int to array

前端 未结 4 1351
难免孤独
难免孤独 2021-01-14 23:35

I\'m asking the user to input 5 numbers and store it into an array so I can send the values in a method and subtract 5 numbers from each array. When I use the:



        
4条回答
  •  暖寄归人
    2021-01-15 00:07

    You're assigning the string input from the Console to an array of int. This is wrong for two reasons:

    1. int arrays (int[]) are a collection of ints.
    2. The value you're getting from the Console isn't an int and needs to be parsed first.

    This is a slight diversion, but I also don't think you should be using an array. Arrays generally have significantly less function in C# than the built-in List. (All the rockstars chime in here) Some people say there's no reason to use arrays at all - I won't go that far, but I think for this use case it'll be a lot easier to just add items to a List than to allocate 5 spaces and initialize values by index.

    Either way, you should use int.TryParse(), not int.Parse(), given that you'll immediately get an exception if you don't check if the user input was parseable to int. So example code for taking in strings from the user would look like this:

    List userInts = new List();
    
    for (int i = 0; i < 5; i++)
    {
        string userValue = Console.ReadLine();
        int userInt;
        if (int.TryParse(userValue, out userInt))
        {
            userInts.Add(userInt);
        }
    }
    

    If you'd still like to use the array, or if you have to, just replace List userInts... with int[] userInts = new int[5];, and replace userInts.Add(userInt) with userInts[i] = userInt;.

提交回复
热议问题