How to deal with the null values of an array when converting from String to Double?

Asked

Viewed 112 times

-1

I need to display the top 10 contract termination clauses, which are in a vector, extracted from a CSV file. Here, when I refer to contract termination clauses, I mean monetary values (money), more precisely for termination fine.

What I thought I’d do?

  1. Convert the column to the values of the String to the guy Double, because there are very high values;
  2. Order from the highest to the lowest;
  3. Convert back to String; and
  4. Add into a List<String>, because that’s what I need to return in the method I’m using.

The problem happens when I try to convert from String for Double, for in that column there are several people without a defined termination clause value, that is, its values are blank, which I understand as null.

If primitive type use double, it returns an exception saying that it is not possible to convert a String in double. If use Double, the exception says that the String is empty.

What can I do to get around this problem?

Snippets of the codes I’m using:

To read the CSV file:

static String[] jogadores;
static Double[] rescisao = new Double[17995];

public static BufferedReader lendoCSV(String arquivo, String separador) {
        BufferedReader conteudoArquivo = null;
        String linha = "";
        boolean cabecalhoLido = false;
        int i = 0;

        try{
            conteudoArquivo = new BufferedReader(new FileReader(arquivo));
            while((linha = conteudoArquivo.readLine()) != null) {
                if(!cabecalhoLido) {
                    cabecalhoLido = true;
                    continue;
                } i++;

                jogadores = linha.split(separador);
                idade[i] = Integer.parseInt(jogadores[6]);
                nomeCompleto[i] = jogadores[2];
                nacionalidade[i] = jogadores[14];
                nomeDosClubes[i] = jogadores[3];
                rescisao[i] = Double.parseDouble(jogadores[18]);
            } 
            System.out.println("A leitura do arquivo deu certo!");
        } catch(FileNotFoundException e) {
            System.out.println("Arquivo não encontrado: \n" + e.getMessage());
        } catch(ArrayIndexOutOfBoundsException e ) {
            System.out.println("Indice fora dos limites: \n" + e.getMessage());
        } catch(IOException e) {
            System.out.println("Erro de entrada de dados: \n" + e.getMessage());
        } finally {
            if(conteudoArquivo != null) {
                try {
                    conteudoArquivo.close();
                } catch(IOException e) {
                    System.out.println("Erro de entrada de dados: \n" + e.getMessage());
                }
            }
        }
        return conteudoArquivo;
    }

When I try to convert to Double, because I tried to use double primitive, I take this exception:

Exception in thread "main" java.lang.Error: Unresolved Compilation problem: Type Mismatch: cannot Convert from double to String

If I try to use Double:

static Double[] rescisao = new Double[17995];

I take this exception:

Exception in thread "main" java.lang.Numberformatexception: Empty String at sun.misc.Floatingdecimal.readJavaFormatString(Unknown Source) at sun.misc.Floatingdecimal.parseDouble(Unknown Source) at java.lang.Double.parseDouble(Unknown Source) at Challenge.Main.lendoCSV(Main.java:46) at Challenge.Main.main(Main.java:171)

Method I am using and that needs to return a List:

public static List<String> maioresClausulasDeRescisao() {
    List<String> clausulas = new ArrayList<String>();
    for(int i = 0; i < 11; i++) {
        clausulas.add(rescisao[i]);
        System.out.println(clausulas);
    }
    return clausulas;
}
  • 1

    Before you see this error there is another major error: https://answall.com/q/219211/101. Double accept null yes. double that does not accept. In what was presented there seems to be no problems, the error must be elsewhere.

  • 1

    You also need to show the rest of the code associated with conversion. jogadores is a String[] ? What value is in jogadores[18] ? What kind of rescisao ?

  • Okay, @Maniero and @Isac! Thank you! I will supplement the question! ^_^

  • I made corrections to the question. :-)

  • 1

    To my knowledge double and float were never types to be used in monetary value.

  • @Guess what kind to use, then?

  • 1

    Bigdecimal is generally used for monetary types.

  • @I’ll try to get.

  • @Articuno, I tried, but the problem is still the blank values.

Show 4 more comments

1 answer

0

The problem must occur because you are trying to build a Double object from an empty String. What makes releasing java.lang.Numberformatexception: Empty String, if it were a null string would also occur error, but it would be a nullpointerexception. You cannot pass to the parseDouble(String s) method, or to the constructor of the Double class an empty or null String. One solution is to test the value before building the object. You can use Try/catch and if the variable of the array you are reading the values from is null or empty, you set a default value to build your Double object and proceed to the program without errors. Below is an example.

    String[] valores = new String[10];
    valores[1] = ""; // teste com null tbm
    Double rescisao;
    try {
        rescisao = Double.valueOf(valores[1]);
    } catch (NumberFormatException | NullPointerException e) {
        e.printStackTrace();
        rescisao = 0.0;
    }

    System.out.println("Rescisao: " + rescisao);

Note: Can replace Double by Bigdecimal.

Browser other questions tagged

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