Summation variables in java

0

I have a double variable declared inside a for loop, this variable returns different values according to the loop through the list array.

for(int i = 0; i < ticketAdapter.mTicket.mLines.size(); i++){
                double totalNoVATt = ticketAdapter.mTicket.mLines.get(i).mTotalNoVAT * ticketAdapter.mTicket.mLines.get(i).mUnits;
                Log.i("MainActivity","totalnovat "+ totalNoVATt);
            }

I wanted to know how to save the sum of these values in a variable that it returns to me.

Greetings.

    
asked by J. Burrueco 05.12.2018 в 10:54
source

2 answers

2

Declare a variable of the same type (Double) outside the loop and you add the amount calculated in each iteration within the loop, something like this:

double sumatoria = 0.0;
for(int i = 0; i < ticketAdapter.mTicket.mLines.size(); i++){
    double totalNoVATt = ticketAdapter.mTicket.mLines.get(i).mTotalNoVAT * ticketAdapter.mTicket.mLines.get(i).mUnits;
    sumatoria += totalNoVATt;
    Log.i("MainActivity","totalnovat "+ totalNoVATt);
}
System.out.println(sumatoria);
    
answered by 05.12.2018 / 11:13
source
0

If you can use Java 8 (or higher), you may prefer:

double sumatorio = ticketAdapter.mTicket.mLines.stream().mapToDouble( m -> m.mTotalNoVAT * m.mUnits ).sum();
    
answered by 05.12.2018 в 16:00