count positives and sum of negatives

hi, im doing an excercise that given an array of integers, I have to return an array, where the first element is the count of positives numbers and the second element is sum of negative numbers. 0 is neither positive nor negative. If the input is an empty array or is null, return an empty array. i've been on this excercise for over 30 minutes but i cant figure out how to do the last step (If the input is an empty array or is null, return an empty array.) can someone help me out figuring out what im missing/ doing wrong? ============= using System; using System.Collections.Generic; using System.Linq; public class Kata { public static int[] CountPositivesSumNegatives(int[] input) { if ((input.Length == 0) || (input == null)) { ; return new int [] {}; } else{ int pos = 0; int neg = 0; foreach (int i in input) { if (i > 0) { pos += 1; } else if (i <= 0){ neg += i; } } if ((pos == 0) && (neg == 0)) { int [] result = {}; return result; } else{ int [] result = {pos, neg}; return result; } } //return an array with count of positives and sum of negatives } }
10 Replies
blueberriesiftheywerecats
Looks like you made the if statement so what the problem? And you dont need the if pos and neg equals 0 Because if for example array contains only ten 0'es then your should just return [0,0]
𝓥𝓪𝓵𝓮𝓷𝓽𝓲𝓷𝓪.🌸
right.. when i run the test for the null case, i get this error got it thanks! ill correct that
blueberriesiftheywerecats
What error
𝓥𝓪𝓵𝓮𝓷𝓽𝓲𝓷𝓪.🌸
System.NullReferenceException : Object reference not set to an instance of an object. sorry it didnt send it xD
blueberriesiftheywerecats
Ohh i see In first if statement swap those checks Like check first if its null then check length
𝓥𝓪𝓵𝓮𝓷𝓽𝓲𝓷𝓪.🌸
now it worked omg
blueberriesiftheywerecats
It throws this error because it cant get Length property from null object
𝓥𝓪𝓵𝓮𝓷𝓽𝓲𝓷𝓪.🌸
ooooo makes sense tysm
blueberriesiftheywerecats
when you use || and the left statement is true, than program will not check the right statement because its useless, so thats why you can have this in this order working Because if it wanted to check the right statement also (even if left was true) then you would still got that error
𝓥𝓪𝓵𝓮𝓷𝓽𝓲𝓷𝓪.🌸
got itt, i didnt know about that! Thank you so much!
Want results from more Discord servers?
Add your server