How to read the .csv file and write it in a list?

0

I'm starting in Java and I'm having trouble reading from a file and publishing to a list. The list is pre-defined.

List<Atleta> listaAtletas = new ArrayList<>();

The Atleta class has no problems and has the following code, along with get and set for the variables nome , idadeGrupo , tempo .

public class Atleta
{
   private static int proximoNumero = 1; //numera automaticamente o numero de atletas criados 

   public int numero;       // numero do atleta
   public String nome;      // nome do atleta
   public String idadeGrupo;  // media, junior ou senior
   public int tempo;         // tempo demurado pelo atleta na maratona

   /**
    * Constructor para os objectos da class Atleta.
    */
   public Atleta() {
      super();
      this.nome = "";
      this.idadeGrupo = "media";
      this.tempo = 0;
      this.numero = this.proximoNumero;
      this.proximoNumero++;

    }

In class MaratonaAdmin I can not read from the file and publish to the list. I do not know what I'm doing wrong in this class.

import java.util.*;
import java.io.*;
/**
 * Class MaratonaAdmin - administra a maratona
 */
public class MaratonaAdmin
{

   private Atleta osAtletas;

   /**
    * Constructor para os objectos da class MaratonaAdmin
    */
   public MaratonaAdmin() {
      List<Atleta> listaAtletas = new ArrayList<>();
      // Para debug
      int tamanho = listaAtletas.size();  
      System.out.println("Tamanho da lista " + tamanho);
   }

   /**
    * Metodo que lê de arquive .CSV
    * Não tem argumento
    * Não retorna valores
    */
   public void lerOsAtletas() {
      FileReader arq = new FileReader("test.csv");
      String nome;
      String idadeGrupo;
      int tempo;
      Scanner linhaScanner;
      String linhaCurrente;
      Scanner bufferedScanner = null;
      bufferedScanner = new Scanner(new BufferedReader(new FileReader("test.csv")));
      try {
         while (bufferedScanner.hasNextLine()) {
            linhaCurrente = bufferedScanner.nextLine();
            linhaScanner = new Scanner(linhaCurrente);
            linhaScanner.useDelimiter(",");
            nome = linhaScanner.next();
            idadeGrupo = linhaScanner.next();
            tempo = linhaScanner.next();
            listaAtletas.add(new Account(accountHolder, accountNumber, accountBalance));
         }
      }
      catch (Exception anException) {
         System.out.println("Erro: " + anException);
      }
      finally {
         try {
            bufferedScanner.close();
         }
         catch (Exception anException) {
            System.out.println("Error: " + anException);
         }
      }
   }
}
    
asked by anonymous 01.05.2017 / 02:28

2 answers

0

In this part:

listaAtletas.add(new Account(accountHolder, accountNumber, accountBalance));
  

You seem to add a Account and not a Atleta .

I think that there is a good part of the error. Other than that, I did not understand how you are creating a new athlete , and adding in the list (is missing code?)

Anyway, I've changed your code (quite, sorry!) for testing, and I believe you can use this code to fix yours:

import java.util.*;
import java.io.*;

public class MaratonaAdmin {

    static List<Atleta> listaAtletas;

    public static void main(String[] args) throws FileNotFoundException {

        listaAtletas = new ArrayList<>();
        lerOsAtletas();

        System.out.println("Tamanho da lista " + listaAtletas.size());

        for (Atleta atl : listaAtletas) {
            System.out.println("Atleta no.: " + atl.numero);
            System.out.println("Nome: " + atl.nome);
            System.out.println("Grupo: " + atl.idadeGrupo);
            System.out.println("Tempo: " + atl.tempo);
            System.out.println("#######");
        }
    }

    public static void lerOsAtletas() throws FileNotFoundException {

        FileReader arq = new FileReader("C://Users//danie//Documents//test.csv");

        Scanner bufferedScanner = new Scanner(new BufferedReader(arq));
        try {
            while (bufferedScanner.hasNextLine()) {
                String linhaCurrente = bufferedScanner.nextLine();
                Scanner linhaScanner = new Scanner(linhaCurrente);
                linhaScanner.useDelimiter(",");
                listaAtletas.add(new Atleta(linhaScanner.next(),
                  linhaScanner.next(), linhaScanner.next()));
                linhaScanner.close();
            }
        } catch (Exception anException) {
            System.out.println("Erro: " + anException);
        } finally {
            try {
                bufferedScanner.close();
            } catch (Exception anException) {
                System.out.println("Error: " + anException);
            }
        }
    }
}
  

I had to change the class Atleta also (for reason explained above):

public class Atleta {
    private static int proximoNumero = 1;   
    public int numero;
    public String nome;
    public String idadeGrupo;
    public String tempo;

    public Atleta(String nome, String idadeGrupo, String tempo) {
        this.nome = nome;
        this.idadeGrupo = idadeGrupo;
        this.tempo = tempo;
        this.numero = Atleta.proximoNumero;
        Atleta.proximoNumero++;
    }
}

In addition, your int tempo; should not work, because the program reads String of .csv , does not it? The conversion will have to be made at another time (I did not include the conversion to simplify the code).

  

.csv used for testing:

stackoverflow,junior,2:02:57
Torre Eiffel,senior,3:14:41
Empire State,media,4:21:18
  

Result:

Tamanho da lista 3
Atleta no.: 1
Nome: stackoverflow
Grupo: junior
Tempo: 2:02:57
#######
Atleta no.: 2
Nome: Torre Eiffel
Grupo: senior
Tempo: 3:14:41
#######
Atleta no.: 3
Nome: Empire State
Grupo: media
Tempo: 4:21:18
#######
    
01.05.2017 / 05:00
0

Your version did not work but it helped me find the error I had in the code. Thanks for the help and here is the complete code.

import java.util.*;
import java.io.*;

/**
 * Class MaratonaAdmin - administra a maratona
 */
public class MaratonaAdmin
{

   //private Atleta osAtletas;
   static List<Atleta> listaAtletas;

   /**
    * Constructor para os objectos da class MaratonaAdmin
    */
   public MaratonaAdmin() throws FileNotFoundException
   {
      listaAtletas = new ArrayList<>();
      lerOsAtletas(); 
      for (Atleta atl : listaAtletas) {
          System.out.println("Atleta no.: " + atl.numero);
          System.out.println("Nome: " + atl.nome);
          System.out.println("Grupo: " + atl.idadeGrupo);
          System.out.println("Tempo: " + atl.tempo);
          System.out.println("#######");
        }

   }

   /**
    * Metodo que lê de arquive .CSV
    * Não tem argumento
    * Não retorna valores
    */
   public static void lerOsAtletas() throws FileNotFoundException
   {
        Scanner bufferedScanner = new Scanner(new BufferedReader(new FileReader("C://Users//danie//Documents//test.csv")));
        try {
            while (bufferedScanner.hasNextLine()) {
                String linhaCurrente = bufferedScanner.nextLine();
                Scanner linhaScanner = new Scanner(linhaCurrente);
                linhaScanner.useDelimiter(",");
                listaAtletas.add(new Atleta(linhaScanner.next(),
                  linhaScanner.next(), linhaScanner.next()));
                linhaScanner.close();
            }
        } catch (Exception anException) {
            System.out.println("Erro: " + anException);
        } finally {
            try {
                bufferedScanner.close();
            } catch (Exception anException) {
                System.out.println("Error: " + anException);
            }
        }
   }
}
    
02.05.2017 / 01:07