-1

I want to get the sum of the stored int values of int[] array. the code still have errors. are there any codes that would make this line of codes look simplified? I want to make the 52 weeks money challenge app without database.

I have this formula: iA + sum = total[] + aA = tA;

I am having an error of the previous value not being added by preceding value.

PS. weeks, iA (Initial Amount), aA (Adding Amount), sum, sT are int. the tA's are now being added to the total[].

PSS: For everyone who flagged this question which have duplicate question, I already saw that question and it doesn't answer what my question is. The post have its own values created by the programmer/coder, I am asking for how to add the previous element to the values of two added integer values. I already tried the solution given in that question, and it's not working for my code. It gives different value (the unwanted value).

int[] total = new int[weeks + 1];
        int sum = 0;
        int tA = 0;
        int ai = 0;

        for(int sT = 1 ; sT <= weeks; sT++){ // error
            sum += iA;
            System.out.println("The payable for the week " + sT + " is: " + sum);
            total[sT] = sum;
            tA = total[sT];
            if(sT == 1){
                System.out.println("if: " + tA);
            }
            else if(sT == 2){
                tA += iA;
                System.out.println("else if: " + tA);
            }
            else{
                tA += aA;
                System.out.println("else: " + tA);
            }
        }
    System.out.println(Arrays.toString(total)); //print stored values of array

2 Answers2

2

If you are on Java 8, you can use

int sum = Arrays.stream(total).sum(); 

Otherwise the old fashioned way

for( int i : total) {
    sum += i;
}
The Lama
  • 21
  • 4
  • I appreciate the effort to add a comment to this thread, but that line of codes is not the answer for this question. I wanted to get the previous value of total and add it to the preceding value of total. – Ruby Rae Olaya Jun 05 '17 at 08:10
0

the question already has an answer.

for(int sT = 1 ; sT <= weeks; sT++){
            sum += iA;
            System.out.println("The payable for the week " + sT + " is: " + sum);
            tA = sum;
            if(sT == 1){
                System.out.println("if: " + tA);
                total[sT] = tA;
            }
            else if(sT == 2){
                tA = iA + sum;
                System.out.println("else if: " + tA);
                total[sT] = tA;
            }
            else{
                tA = sum + total[sT - 1];
                System.out.println("else: " + tA);
                total[sT] = tA;
            }
        }
    System.out.println(Arrays.toString(total)); //print stored values of array