java.lang.ArrayIndexOutOfBoundsException: 0 when using split () in java [duplicate]

1

On the occasion of rounding a number up or down according to decimals, I created a small method in java. The problem that I find is that just the line after applying split() returns the error java.lang.ArrayIndexOutOfBoundsException: 0 .

I leave an example:

double descuento_pais = 59.5;                                       
double descuento_pais_final = damedescuento(descuento_pais);

public double damedescuento (double descuento) {

        String descuento_string = String.valueOf(descuento);
        String[] parts = descuento_string.split(".");
        String entero = parts[0]; 
        String decimal = parts[1]; 
        double descuento_pais;

        if (Double.parseDouble(decimal) >= 0.5) {
            descuento_pais = Double.parseDouble(entero) + 1;
        } else {
            descuento_pais = Double.parseDouble(entero);
        }

        return descuento_pais;
    }
    
asked by JetLagFox 03.12.2017 в 02:11
source

1 answer

1

The problem is that String.split(String) expect you to provide a regular expression. And the point has special meaning in regex.

To interpret the point literally, you must escape it with \ :

String[] parts = descuento_string.split("\.");
    
answered by 03.12.2017 / 02:16
source