Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading