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:
You're assigning the string input from the Console to an array of int. This is wrong for two reasons:
int
arrays (int[]
) are a collection of ints
.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
... with int[] userInts = new int[5];
, and replace userInts.Add(userInt)
with userInts[i] = userInt;
.