How to read from a file and save on variables in Java

3

I'm having a hard time, because in an exercise of manipulating files in Java, the teacher asked us to create a program that takes the name and note 1 and note 2 of two tests and store in a txt file of the following form: name, note1, nota2 only then in another exercise it asks to read from the file the data and calculate the average of the notes saving again the data in another file as follows: note1; nota2; media, as I do this reading and save the data into String, float, float variable again ???

public class LeitorComun extends Leitor {
    private String nome;
    private  double n1,n2,media;
    String linha;

    public LeitorComun(FileInputStream arquivo) {
        super(arquivo);
    }


     @Override
    public void ler() throws IOException{
        InputStreamReader isr = new InputStreamReader(this.arquivo);
        BufferedReader br = new BufferedReader(isr);
        do{
        this.linha = br.readLine();
              if(this.linha != null){
                  String [] palavras = this.linha.split(";");
                  System.out.println("nova linha ------------------------------------");
                  for(int i =0; i<palavras.length;i++){
                      System.out.println("palavra lida: "+ palavras[i]);
                  }
              }
          }while(this.linha != null);

    }
}
    
asked by anonymous 18.11.2016 / 13:19

1 answer

1

You can create a simple method for converting String to double :

private double converter(String texto) {
  return Double.parseDouble(texto);
}

And change your method ler to:

@Override
public void ler() throws IOException {
  InputStreamReader isr = new InputStreamReader(this.arquivo);
  BufferedReader br = new BufferedReader(isr);

  do {
    this.linha = br.readLine();

    if (this.linha != null) {
      double nota1;
      double nota2;
      double media;

      try {
        String[] palavras = this.linha.split(";");
        System.out.println("nova linha ------------------------------------");
        nota1 = this.converter(palavras[1]);
        nota2 = this.converter(palavras[2]);
        media = (nota1 + nota2) / 2;
        System.out.println(palavras[0] + "/ Média: " + media);
      } catch (NumberFormatException ex) {
        System.out.println("A linha \"" + this.linha + "\" contém erros");
      }
    }
  } while (this.linha != null);
}

With the following file notas.txt :

  

José; 10; 9

     

André; 5; 8

The result is:

nova linha ------------------------------------
José/ Média: 9.5
nova linha ------------------------------------
André/ Média: 6.5
    
18.11.2016 / 15:44