3

Cada objeto do tipo aluno instanciado anteriormente deve ser inserido em um vetor de objetos do tipo Aluno. Para este exercício você pode assumir que o vetor tenha no máximo 5 posições. Para criar um objeto do tipo aluno a partir da linha lida do arquivo utilize o método split da classe String. Depois de carregar o vetor com os objetos instanciados a partir do arquivo, itere por ele e para cada aluno mostre na tela o nome e a média das notas.

O que falta?

public class Aluno {

protected String matricula;
protected String nome;
protected Float notaGA;
protected Float notaGB;

public Aluno(String matricula, String nome, Float notaGA, Float notaGB) {

    this.matricula = matricula;
    this.nome = nome;
    this.notaGA = notaGA;
    this.notaGB = notaGB;
}



public Aluno(String nome, String notaGA, String notaGB) {
    super();
}



public String getMatricula() {

    return matricula;
}

public void setMatricula(String matricula) {

    this.matricula = matricula;
}

public String getNome() {

    return nome;
}
public void setNome(String nome) {

    this.nome = nome;
}
public Float getNotaGA() {

    return notaGA;
}
public void setNotaGA(Float notaGA) {

    this.notaGA = notaGA;
    }
public Float getNotaGB() {

    return notaGB;
    }
public void setNotaGB(Float notaGB) {

    this.notaGB = notaGB;
    }
public String toString(){
       return String.format("Matricula: %s\nNome: %\nNota GA: %\nNota GB:%s\r\n", 
               getMatricula(),
               getNome(),
               getNotaGA(),
               getNotaGB());
       }

}

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;


public class CarregaAlunos{

    protected static Aluno constroiAluno(String linha){
        String atributos[] = linha.split(",");
        Aluno a = new Aluno(atributos[0], atributos[1], atributos[2]);
        return a;
    }
    public static Aluno[] carregaArquivo(String arquivo) throws IOException{
        Aluno alunos[]    = new Aluno[5];
        FileReader fr = new FileReader(arquivo);
        BufferedReader br = new BufferedReader(fr);
        String linha;
        int cont = 0;
        while ((linha = br.readLine()) != null){
            Aluno a = constroiAluno(linha);
            alunos[cont] = a;
            cont++;

        }


        br.close();
        return alunos;

 }

    public static void main(String[] args) {

    try{
    Aluno a[] = carregaArquivo("alunos.txt");

    for (int i=0; i < a.length; i++){

    System.out.println(a[i]);

    }

    }

    catch(IOException e){

    e.printStackTrace();

    }

    }
}

alunos.txt

Alex,8.5,9.5
Paulo,9.4,10
Pedro,6.5,8.7
Ana,9.1,8.3
Carlos,7.7,8.1
3

1 Resposta 1

1

Seu código ficou muito bom, só faltaram pequenos detalhes. Rodei aqui e fui adaptando.

Primeiro problema: O caminho do arquivo tem que estar completo. Coloquei o arquivo em c:\ e no nome de arquivo passei "C:\\alunos.txt" (repare que tem duas barras pra uma escapar a outra e o java não achar que estou querendo escapar a letra 'a' de alunos) e parou de dar exceção dizendo que não conseguiu achar o arquivo.

Segundo problema: Não entendi porque chamou super no segundo construtor ao invés de fazer como foi feito o primeiro. super se usa pra chamar métodos de uma classe pai, como sua classe não extende nenhuma outra, não entendi o super(). Então mudei o super() para:

    this.nome = nome;
    this.notaGA = Float.parseFloat(notaGA);
    this.notaGB = Float.parseFloat(notaGB);   

Terceiro problema: Achei interessante que usou o String.format mas você comeu alguns s onde deveria ser %s. Corrigido ficou:

Matricula: %s\nNome: %s\nNota GA: %s\nNota GB:%s\r\n

Por sugestão da IDE mudei a iteração do array para um foreach:

     for (Aluno a1 : a)
     {
         System.out.println(a1);
     }

Seguem os arquivos modificados funcionando:

Aluno.java

public class Aluno 
{
    protected String matricula;
    protected String nome;
    protected Float notaGA;
    protected Float notaGB;


    public Aluno(String matricula, String nome, Float notaGA, Float notaGB) 
    {

        this.matricula = matricula;
        this.nome = nome;
        this.notaGA = notaGA;
        this.notaGB = notaGB;
    }


    public Aluno(String nome, String notaGA, String notaGB) 
    {
        //super(); // ?

        this.nome = nome;
        this.notaGA = Float.parseFloat(notaGA);
        this.notaGB = Float.parseFloat(notaGB);   
    }


    public String getMatricula() 
    {
        return matricula;
    }

    public void setMatricula(String matricula) 
    {
        this.matricula = matricula;
    }

    public String getNome() 
    {
        return nome;
    }

    public void setNome(String nome) 
    {
        this.nome = nome;
    }

    public Float getNotaGA() 
    {
        return notaGA;
    }

    public void setNotaGA(Float notaGA) 
    {
        this.notaGA = notaGA;
    }

    public Float getNotaGB() 
    {
        return notaGB;
    }

    public void setNotaGB(Float notaGB) 
    {
        this.notaGB = notaGB;
    }

    public String toString()
    {
        return String.format("Matricula: %s\nNome: %s\nNota GA: %s\nNota GB:%s\r\n", 
                getMatricula(),
                getNome(),
                getNotaGA(),
                getNotaGB());
    }

}

CarregaAlunos.java

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;


public class CarregaAlunos
{
    protected static Aluno constroiAluno(String linha)
    {
        String atributos[] = linha.split(",");
        Aluno a = new Aluno(atributos[0], atributos[1], atributos[2]);
        return a;
    }

    public static Aluno[] carregaArquivo(String arquivo) throws IOException
    {
        Aluno alunos[]      = new Aluno[5];
        FileReader fr       = new FileReader(arquivo);
        BufferedReader br   = new BufferedReader(fr);
        String linha;

        int cont = 0;
        while ((linha = br.readLine()) != null)
        {
            Aluno a = constroiAluno(linha);
            alunos[cont] = a;
            cont++;
        }


        br.close();
        return alunos;

 }

    public static void main(String[] args) 
    {
        try
        {
            Aluno a[] = carregaArquivo("C:\\alunos.txt");

            for (Aluno a1 : a)
            {
                System.out.println(a1);
            }

        }
        catch(IOException e)
        {
            e.printStackTrace();
        }

    }

}

Qualquer dúvida pergunte nos comentários. Se essa resposta tiver te ajudado, dê uma moral marcando como resposta aceita e clicando na setinha para cima para me dar pontos de reputação.

1
  • Obrigado pela ajuda!
    – Ricardo
    16/03/2017 às 2:03

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .