Add number of a txt file

Asked

Viewed 345 times

0

Here’s the thing, I’m using this method to read my txt file.

 public String lerArquivo2() throws FileNotFoundException, IOException {

        FileInputStream input = context.openFileInput("teste46a.txt");
        int byteLido = 0;

        StringBuffer str = new StringBuffer();

        while ((byteLido = input.read()) != -1) {
            str.append((char) byteLido);


        }
        System.out.print(str);
        return str.toString();
    }

And within this txt are the numbers 7.0 6.5 6.0 12.0 I need to sum all these numbers the final result would have to be 31.5.

How can I do that?

1 answer

2

You can do it this way:

String aSeparar = lerArquivo2();

String stringNumeros[] = aSeparar().split(" ");

float total = 0f;

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

    float numero = Float.parseFloat(stringNumeros[i]);
    total += numero;

}

Browser other questions tagged

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