Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# user input int to array

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:

for(I=0;I<5;I++) {
int[] val = Console.ReadLine();}

It says I can't convert int[] to int. I'm a little rusty in my programming. I also don't know how to send the array values from the main to the method.

like image 642
Voix Avatar asked Jan 29 '26 21:01

Voix


2 Answers

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<T>. (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<int> userInts = new List<int>();

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<int> userInts... with int[] userInts = new int[5];, and replace userInts.Add(userInt) with userInts[i] = userInt;.

like image 143
furkle Avatar answered Feb 01 '26 10:02

furkle


You initialize the array first

int[] val = new int[5];

and then when you do a for loop:

for (int i=0; i<val.Length; i++)
{
   val[i] = int.Parse(Console.ReadLine());
}

Hint: To send the array values from main to the method, just look at how static void main is formed:

static void Main(string[] args)

Meaning main is accepting a string array of of console arguments.

like image 36
Tyress Avatar answered Feb 01 '26 09:02

Tyress



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!