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
Clear an Array Using the fill () Method in Java This method is another solution where we used the fill () method of the Arrays class to clear an array by setting a new value. After using the fill () method, we used the for-loop to access its elements and see if all the parts have cleared.
This example demonstrate about How to delete all elements from arraylist for listview in Android Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml.
If you want to make an array entirely empty (i.e., no element, even no default elements), you can assign a null reference to the array object. After making an array null, don’t try to access its elements, or else the compiler will return the NullPointerException command. Check the example code below:
You would need to create a new (smaller) array, and copy the elements you wished to preserve into it. A better Idea would be to use a List implementation that was dynamic. An ArrayList<Integer> for example. Show activity on this post. Arrays in Java are not dynamic, you can use an ArrayList instead.
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;
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With