Skip to content
Advertisement

How to obtain the last number different to zero in an array in Java

I have for example this array:

JavaScript

And I want to find the last number of the array different to 0. In this case, my output should be: 9.0

My code is:

JavaScript

But it doesn’t work.

I need to highlight that the size of the array1 is always the same. But the non-zero numbers can change, in any case, all the zeros will be at the end of the array always.

I need also have array2, obtained by array1.

Furthermore, all the numbers are always positive.

Advertisement

Answer

Here is one way using a loop and the ternary operator (a ? b : c says if a is true return b, else return c)

JavaScript
  • initialize last to 0.
  • iterate over array
  • if current value (i) == 0, return last.
  • else return i
JavaScript

prints 9.0

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement