Merve Gül
Merve Gül

Reputation: 1397

Hold integer inputs into an array

I am trying to hold integer inputs into an array but it doesn't work. I found an example for string hold from How to Fill an array from user input C#?

string[] yazi = new string[15];
for (int i = 0; i < yazi.Length; i++)
{
      yazi[i] = Console.ReadLine();
}

But when I turn this code to integer, it gave an error

int[] sayis = new int[20];
for (int k = 0; k < sayis.Length; k++)
{
      sayis[k] = int.Parse(Console.ReadLine());
}

Am I missing something?

Upvotes: 1

Views: 2343

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500275

Am I miss something?

The error message, for one thing...

It should be fine - so long as you type integers into the console. (I've just tried it, and it worked perfectly.) If the user enters a value which can't be parsed as an integer, you'll get a FormatException. You should consider using int.TryParse instead... that will set the value in an out parameter, and return whether or not it actually succeeded. For example:

for (int k = 0; k < sayis.Length; k++)
{
    string line = Console.ReadLine();
    if (!int.TryParse(line, out sayis[k]))
    {
        Console.WriteLine("Couldn't parse {0} - please enter integers", line);
        k--; // Go round again for this index
    }
}

Upvotes: 6

Related Questions