简体   繁体   中英

C# checking if next value in array is null

This code cycles thru an array of integers, adding the int at the current index with the int at the next index (i + 1) and then finding their average (dividing by 2). This double is then appended to an array of doubles. When I get to the end of the array however, since there is no value beyond the last value, an error occurs. I thought I could just check to see if the value was null but the error is occurring beforehand. Error occurs at line 15 "if (numbers[i + 1].= null)."

using System;
using System.Collections;
using System.Linq;

public class Test
{
    public static double[] Averages(int[] numbers)
    {
        double[] averageArray = new double[0];
        for (int i = 0; i < numbers.Length; i++)
        {
            double sum = 0;
            double avg = 0;

            if (numbers[i + 1] != null)
            {
                sum += numbers[i] + numbers[i + 1];
                avg = sum / 2;
            }
            averageArray = averageArray.Append(avg).ToArray();
        }
        return averageArray;
    }

    public static void Main()
    {
        int[] testArray1 = { 2, 2, 2, 2 };
        Console.WriteLine(Averages(testArray1));
    }
}

Ok, so, couple of things that need to be considered with your code. How you have it right now will throw an out of range exception.

You should never be able to have a null object in your int array so thats not a check you need to do.

If you need it to accept nulls, you need to declare it as int?[]

The way you have your code now, the output \ return value is an array of 5 values, when you have 4 going in

2, 2, 2, 1, 0

void Main()
{
    int[] testArray1 = { 2, 2, 2, 2,  };
    Console.WriteLine(Averages(testArray1));
}

public static double[] Averages(int[] numbers)
{
    double[] averageArray = new double[0];
    for (int i = 0; i <= numbers.Length; i++)
    {
        double sum = 0;
        double avg = 0; // This will cause a last object to be added to your array

        if (i == numbers.Length - 1) // This adds the last item, this also needs to have order or preference as this would also then cause a Index Out of Range Exception 
        {
            sum += numbers[i];
            
        }
        else if(i <= numbers.Length -1) // This adds all items that are not the last item in the array
        {
            sum += numbers[i] + numbers[i + 1];
        }
        avg = sum / 2;
        averageArray = averageArray.Append(avg).ToArray();
    }

    return averageArray;
}

输出

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM