5

I have an example that calculates total expense and income. There are some values in integer array that converted from a string array. Once I am running the code the sum is 6000 and running again the same code the sum gets multiplied to 12000. How can I override this problem. Please check my code given below..

public static int incSum=0;

int[] numbersinc = new int[theAmount.length];

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

        numbersinc[i]=Integer.parseInt(theAmount[i]);

        incSum=incSum+numbersinc[i];
    }

    Log.e("SUM INC","Sum Inc= "+incSum);    <<<<<- This sum is multiplying
Himanshu Agarwal
  • 4,623
  • 5
  • 35
  • 49
Reshmin
  • 95
  • 1
  • 5
  • 17
  • 1
    This doesn't look like a complete code snippet and is more relevant as a java question rather than android. – Ben Neill Dec 30 '14 at 06:31
  • 1
    It looks like your issue is more to do with the sum not being reset rather than an issue with arrays. Reset the incSum = 0 before each run over the array (that is, before the for loop). – Ben Neill Dec 30 '14 at 06:34

2 Answers2

12

You can simply assign null to the reference. (This will work for any type of array, not just ints)

int[] arr = new int[]{1, 2, 3, 4};
arr = null;

This will 'clear out' the array. You can also assign a new array to that reference if you like:

int[] arr = new int[]{1, 2, 3, 4};
arr = new int[]{6, 7, 8, 9};

If you are worried about memory leaks, don't be. The garbage collector will clean up any references left by the array.

Another example:

float[] arr = ;// some array that you want to clear
arr = new float[arr.length];

This will create a new float[] initialized to the default value for float.

So in your code try this:

public int incSum=0;

int[] numbersinc = new int[theAmount.length];
incSum = 0; //add this line
    for(int i=0;i<theAmount.length;i++)
    {

        numbersinc[i]=Integer.parseInt(theAmount[i]);

        incSum=incSum+numbersinc[i];
    }

    Log.e("SUM INC","Sum Inc= "+incSum);    <<<<<- This sum is multiplying
  numbersinc = null;
Himanshu Agarwal
  • 4,623
  • 5
  • 35
  • 49
1
public static int incSum=0; 

your variable is static so when you run again then previous value store in incSum variable .

Remove static from incSum

Amit Kumar
  • 547
  • 3
  • 10