0

Im making a method that is passed an array of positive and negative numbers. Im trying to return an array of the count of positive integers, aswell as the sum of the negative ones. Im fairly new to the ternary but im trying to implement one into this for practice. Getting an unexpected type error in my ternary. Was wondering if anyone could give some pointers

public static int[] countPositivesSumNegatives(int[] input)
{
  int[] answer = new int[2];
    for(int i=0; i<=input.length; i++){
      input[i] > 0 ? answer[0] += 1 : answer[1] += input[i];
    }
  return answer;
}
ntg_908
  • 57
  • 7

1 Answers1

1

Ternarys return a value, not an expression. Your structure is more like a standard if-else.

The correct ternary structure looks like this:

value = condition ? true-value : false-value;

Since you're manipulating answer[1] on false and answer[0] on true, a ternary doesn't really make sense here. You'd need two of them to get both the index and the increment value. For the sake of answering your question though, here's an example:

int index = input[i] > 0 ? 0 : 1;
int value = input[i] > 0 ? 1 : input[i];
answer[index] += value;

At this rate, you might as well just use an if-else

if(input[i] > 0)
    answer[0] += 1;
else
    answer[1] += input[i];
Liftoff
  • 24,717
  • 13
  • 66
  • 119
  • Thank you, i was under the assumption that it was a replacement for a standard if else. I have been able to use the ternary on returns in methods, which makes sense after reading your explanation. Thanks allot ! – ntg_908 May 12 '22 at 05:46
  • No problem. At least in Java, you're not supposed to use ternarys this way. That isn't to say it's not possible in other languages, but in Java it's a no go – Liftoff May 12 '22 at 05:51