Splitting always 0 even with variables having values. Bug List/Arraylist

Asked

Viewed 35 times

2

I’m training statistics so I started doing a little program to calculate the percentile. The problem/bug occurs during division always returning 0 even with variables having values.

public static void main(String[] args) throws Exception {
    Float[] valores = new Float[] { 2f, 2f, 3f, 4f, 4f, 9f };
    System.out.println(percentilIgualAbaixo(valores, 3));
}

public static int percentilIgualAbaixo(Float[] array, float value) {
    List<Float> arr = Arrays.asList(array);
    int indexValue = arr.lastIndexOf(value) + 1;

    System.out.println("Index value:" + indexValue);
    System.out.println("tamanho list:" + arr.size());
    return indexValue / arr.size();
}

Exit:

Index value:3
tamanho list:6
0

1 answer

2


That’s not bug, is a very well defined behaviour in language specification.

Basically, if both operands are int, the result of the split will also be int, and the value is rounded. So when dividing 3 by 6 the result is zero (because the result of the division, which is 0.5, is rounded down resulting in the whole value 0).

If you want the result to have decimal places, then the return of the method cannot be int. You’d have to change to float or double, and to do the math, would have to do the cast to force values to one of these types. Something like this:

// muda o retorno do método para float
public static float percentilIgualAbaixo(Float[] array, float value) {
    List<Float> arr = Arrays.asList(array);
    int indexValue = arr.lastIndexOf(value) + 1;
    System.out.println("Index value:" + indexValue);
    System.out.println("tamanho list:" + arr.size());

    // faz o cast dos valores para float
    return (float) indexValue / arr.size();
}

Thus, the result will have decimal places. In your example, with 3 and 6, the result will be 0.5.

Also note that you don’t need to create the list temp, can take the return of Arrays.asList directly.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.