-1

Hello i need to replace the Nan values with 0 in my array in java, any help thanks. you can find the example of my array.

The array type is double and the contents of array are as follows.

x = [ 1 , 2, Nan , 4, Nan ] 
Gautham M
  • 4,816
  • 3
  • 15
  • 37
Bingo
  • 27
  • 4

2 Answers2

6

Loop the array and use isNaN method from Double to check if the number is NaN.

for(int i=0; i<array.length; i++){
    if(Double.isNaN(array[i])) {
        array[i] = 0d;
    }
}
Gautham M
  • 4,816
  • 3
  • 15
  • 37
2

In Java Nan != Nan evaluates to true.

double[] x = { 1 , 2, Double.NaN , 4, Double.NaN};
System.out.println(Arrays.toString(x));
for (int i = 0; i < x.length; i++) {
    if(x[i]!=x[i]) {
        x[i] = 0;
    }
}
System.out.println(Arrays.toString(x));

Output:

[1.0, 2.0, NaN, 4.0, NaN]
[1.0, 2.0, 0.0, 4.0, 0.0]
the Hutt
  • 16,980
  • 2
  • 14
  • 44