Home > other >  Why I get the message"Value cannot be null" in the following code:
Why I get the message"Value cannot be null" in the following code:

Time:10-07

string[] numbers = new string[10];
bool found = false;
for(int i = 0; i < numbers.Length; i  )
{
    numbers[i] = Console.ReadLine();
    if(numbers[i] == "x")
    {
        break;
    }
}
for (int i = 0; i < numbers.Length; i  )
{
    if(numbers[i] != "x")
    {
        if (Int32.Parse(numbers[i]) % 2 == 0)
        {
            found = true;
            Console.WriteLine(numbers[i]);
        }
    }
}
if(found == false)
{
     Console.WriteLine("N/A");
}
Console.ReadLine();

The following message is shown: Unhandled exception. System.ArgumentNullException: Value cannot be null. (Parameter 's') at System.Int32.Parse(String s)

The program continouslly ask for user inputed integers, until "X" is introduced. It will show the even numbers from user inputs.

CodePudding user response:

Your intent here is to stop populating the array once the user enters "x":

if(numbers[i] == "x")
{
    break;
}

And if the array isn't fully populated, the rest of its contents are null values.

Then in the following loop you never break from the loop at all, always trying to process every element in the array. But any element after "x" will be null.

You can also check for null in your condition:

if(numbers[i] != "x" && numbers[i] != null)

Or potentially break from the second loop when you encounter "x":

for (int i = 0; i < numbers.Length; i  )
{
    if(numbers[i] == "x")
    {
        break;
    }
    if (Int32.Parse(numbers[i]) % 2 == 0)
    {
        found = true;
        Console.WriteLine(numbers[i]);
    }
}

Other approaches could include using a List<string> instead of a string[] array, since a List<> is not fixed size and only needs to be populated with the values you want.

  •  Tags:  
  • c#
  • Related