Since starting this course and seeking to join this forum, I have learned a lot and want to thank everyone for their assistance on my own forum questions as well as those I have read during research in this forum.

Having said that I have another array question. I now know how to set each array variable to its own array position with the (for) statement as well as assigning values to each array. My question is how do I sum the content values of an array? My program stores a value into each array position but if I change the value of an array position the total does not reflect when I use this code...

sum += array[value]; // Keeps adding the user input values

Example:
If my array is array[] = {1,2,3,4,5} then the code above sum it to be 15 (this is good...BUT!!!)

If I change the value of the third array position from 3 to 1 (while the program is still active and using the code above) to example array[] = {1,2,1,4,5} then the above code sum it to be 17 (this is not good because I need it to be 13)

Sequence of function:
- User input array position and its value for each and hit a store button from a GUI each time (1,2,3,4,5)
- User hits a second button to total the results of all entries (total = 15)
- User proceeds to change array position 2 to new value 1 by inputting and again press store button (this time array position 2 and value 1)
- User selects the second button to re-evaluate the total (The new total needs to be 13 and not 17)

Thanks,
Jems

very interesting. why dont you display the entire program? just one line of code is not enough to debug. you might be doing something else elsewhere which changes some values.

I wouldn't have sum be a variable that you are keeping track of -- that can get rly confusing. Instead, use a method like this:

public static int getSum(int[] arr)
{
    int sum = 0;
    for (int i = 0; i < arr.length; i++)
    {
        sum += arr[i];
    }
    return sum;
}

Then every time they want the sum of the array just call getSum() on the array and it will return the sum. That way you don't have to keep track of the sum as they change around values.

I wouldn't have sum be a variable that you are keeping track of -- that can get rly confusing. Instead, use a method like this:

public static int getSum(int[] arr)
{
    int sum = 0;
    for (int i = 0; i < arr.length; i++)
    {
        sum += arr[i];
    }
    return sum;
}

Then every time they want the sum of the array just call getSum() on the array and it will return the sum. That way you don't have to keep track of the sum as they change around values.

Nice...thank you, worked like a charm.

Cheers,
Jems

This question has already been answered. Start a new discussion instead.