0

This java codingbat problem is very very easy but, I was told to do it only using ternary operators. Here is the prompt:

Given an int array of any length, return a new array of its first 2 elements. If the array is smaller than length 2, use whatever elements are present.

public int[] frontPiece(int[] nums) {
    return nums.length < 1 ? {} : nums.length < 2 ? { nums[0] } : { nums[0], nums[1]};
}

What am i doing wrong? Why doesn't my code compile?

10 Replies
  • 426
  • 9
  • 25

1 Answers1

0

Change your return statement to:

return nums.length < 1 ? new int[] {} : (nums.length < 2) ? new int[] {nums[0]} : new int[] {nums[0], nums[1]};
SMA
  • 36,381
  • 8
  • 49
  • 73