-1
int[] material = {6255,6255,5003};
int sumQuan = 0;
int []quantity = {6,5,1};
String []calc = {"1","1","0"};
int len = material.length;
int a = material[0];  

for(int i = 0; i < len; i++)
{
    if(a==material[i] && calc[i]=="1")
    {
        sumQuan = sumQuan+quantity[i];                                                       
    }                             
    else if(calc[i]=="0"){
        sumQuan = 0;
    }
    else
    {
        sumQuan = quantity[i];
    }
    System.out.println(sumQuan);
}

I want to return 11,0 but it is returning 6,11,0.

mwerschy
  • 1,698
  • 1
  • 15
  • 26
vardit
  • 29
  • 6

1 Answers1

1

You have to initialize sumQuan to 0 at the beginning/end of the loop, for every iteration. Also, assuming your array is sorted, you have to keep increasing the index and not reset the sum as long as the item was equal to the previous one. Like this:

sumQuan = 0;
for(int i = 0; i < len; i++)
{
    if(calc[i].equals("1"))
    {
        sumQuan = sumQuan+quantity[i];                                                       
    }                             
    // we don't need to do anything if it's "0"
    if ((i < material.length-1 && material[i+1] != material[i])
         || (i == material.length-1)) {
        System.out.println(sumQuan);
        sumQuan = 0;
    }

}

This way you'll keep adding to the sum while you have the same value in material.

If you just want to change your code a little, you can leave the print statement in the else branch of the (a == material[i]) condition. It will only output as long as the item is not equal to the first one.

anana
  • 1,461
  • 10
  • 11