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

Asked

Viewed 470 times

0

I’m starting in Java and I’m having trouble reading from a file and publishing in a list. The list is of predefined type.

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

The class Atleta presents 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 is that I can’t read from the file and publish it on the list. I don’t 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);
         }
      }
   }
}

2 answers

1

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 mistake. Other than that, I did not understand how you are creating a athlete new, and adding to the list (code is missing?)

Anyway, I changed your code (quite, sorry!) to run some tests, 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++;
    }
}

Besides, your int tempo; should not work as the program reads String of .csv, Isn’t it? The conversion will have to be done at another time (I didn’t 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

Upshot:

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
#######

0

Your version didn’t work but it helped me find the error in the code. Thanks for the help and here’s the full 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);
            }
        }
   }
}
  • Why didn’t my code work? Was there an error? (Important to know for me to edit the answer) - if my reply helped you, please click the 'accept' button next to it.

  • The result I pasted is itself output of the program - I know this isn’t usually an excuse, but, "in my machine it rotates"... :p

Browser other questions tagged

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