Home > Mobile >  How to obtain the first number different to zero in an array in Java
How to obtain the first number different to zero in an array in Java

Time:04-01

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.

CodePudding user response:

You need to start at the end of the array, not the beginning:

public static double getLastNonZero(double [] data) throws Exception {
    for (int i = data.length-1; i >=0; i--) {
        if (data[i] != 0) {
            return data[i];
        }
    }
    
    throw new Exception("No value found");
}
public static void main(String[] args) {
    
    double array1[] = {2.3, 5.0, 4.7, 8.2, 1.8, 9.0, 0, 0, 0, 0, 0, 0};
    try {
        System.out.println(getLastNonZero(array1));         
    } catch (Exception e) {
        e.printStackTrace();
    }
}

CodePudding user response:

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

CodePudding user response:

tl;dr

Arrays
    .stream( myArray ) 
    .filter( d -> d != 0 )
    .reduce( ( first , second ) -> second   ) 

DoubleStream

Not necessarily the best approach, but we can use streams. Specifically, DoubleStream.

After producing the stream from our array, filter out zero values. Then retrieve the last element by calling reduce.

We end up with an OptionalDouble object that either contains our resulting double primitive or is empty which means no matches were found in our original array.

double[] doubles = { 1.0d , 2.2d , 3.3d, 0d , 0d } ;
OptionalDouble result = 
    Arrays
    .stream( doubles ) 
    .filter( d -> d != 0 )
    .reduce( ( first , second ) -> second   ) 
;

Dump to console.

System.out.println( result ) ;

See this code run live at IdeOne.com.

OptionalDouble[3.3]

  • Related