I have for example this array:
double array1[] = {2.3, 5.0, 4.7, 8.2, 1.8, 9.0, 0, 0, 0, 0, 0, 0};
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:
double array1[] = {2.3, 5.0, 4.7, 8.2, 1.8, 9.0, 0, 0, 0, 0, 0, 0}; double array2[] = array1.length; double num; for (int i = 0; i < array1.length; i++){ array2[i] = array1[i]; if(array2 != 0){ num = array[i-1]; } }
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
)
double array1[] = {2.3, 5.0, 4.7, 8.2, 1.8, 9.0, 0, 0, 0, 0, 0, 0};
- initialize last to 0.
- iterate over array
- if current value (i) == 0, return last.
- else return i
double last = 0; for(double i : array1) { last = i == 0 ? last : i; } System.out.println(last);
prints 9.0