Error Conversion String to Int

2

I'm doing a simple program, where it reads a .csv file (Excel) and then generates a graph of it. But I'm having trouble converting from String to Int. Below is the Button event code:

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
  FileDialog abrir = new FileDialog(new Dialog(this),"Abrir arquivo",FileDialog.LOAD);
  abrir.setVisible(true);
  File arquivo = new File(abrir.getDirectory()+abrir.getFile());
  XYSeries temp = new XYSeries("Temperatura");

    try {
        String linhaDoArquivo;
        Scanner lerArquivo = new Scanner(arquivo);
        while(lerArquivo.hasNext()){
            linhaDoArquivo = lerArquivo.next();
            String[] valores = linhaDoArquivo.split(",");
            int instante = Integer.parseInt(valores[0]);
        }
    } catch (FileNotFoundException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }
    XYSeriesCollection dataset = new XYSeriesCollection();
    dataset.addSeries(temp);

    JFreeChart chart = ChartFactory.createXYLineChart("Temperatura", "Instante", "Temperatura", dataset, PlotOrientation.VERTICAL, true, true, false);

    ChartPanel panel = new ChartPanel(chart);
    jPanel1.removeAll();
    jPanel1.add(panel, BorderLayout.CENTER);
    jPanel1.validate();

}  
    
asked by anonymous 04.02.2016 / 06:40

1 answer

2

This code assumes that the first field of each line in the CSV is an integer:

        String[] valores = linhaDoArquivo.split(",");
        int instante = Integer.parseInt(valores[0]);

However, it is common to have headers in the CSV with the title of each column, which would cause a NumberFormatException:

  

java.lang.NumberFormatException: For input string: "ID"       at
                  java.lang.NumberFormatException.forInputString (NumberFormatException.java:65)

So the solution is to adjust the CSV or, even better, to protect the code:

String[] valores = linhaDoArquivo.split(",");

try {
      int instante = Integer.parseInt(valores[0]);
} catch (NumberFormatException e){
    //algo deu errado. Tratar aqui
    System.err.println(valores[0] + " não é numérico!");
}
    
10.03.2017 / 05:43