• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

Total values in an Array - Java

Tarrant64

Diamond Member
Right now since there was only a few values I had to total in an array I just did it the long way:

ex: sum of all hours worked in a work week stored in an array( of 5)

totalHours = hours[0] + hours[1] + hours[2] + hours[3] + hours[4]

Any shorter way to do this? I was fortunate enough to only have an array of 5 elements, however I know I should plan for cases of any variable length.
 
for loop.

Lets say you have an array of int named "intArray" that has length of 5.


This will work with an array of any size. You may want to make your "total" variable a long instead of an int if you think there is a chance your total may overflow the maximum value an int can hold. (Following code sample in Java).


GRRRR. . .stupid forum munged up my code formatting :| WHY would you have a programming forum that doesn't preserve formatting of code samples?
 
Java 5 has an improved for loop iteration with better syntax:

Edit: I echo your sentiments - at one time, the attach-code worked correctly
 
this is a good case for the improved for loop - also called for each loop - this came in in java 5 i believe and works with arrays & collections - here is Java's tutorial on it:

http://java.sun.com/docs/books.../nutsandbolts/for.html


but you want:

//assuming you have an int array - change the type to match the array and the counter variable
int totalHours = 0;
for (int total: hours) {
totalHours += hours;
}

this will step completely through the array without having to worry about out of bounds errors, etc


edit - at work so i may have that syntax off a bit but the link is for Sun's Tutorial and they have lots of good stuff there

more edit - ok it is clear to me now - this is how that should look
int totalHours = 0;
for (int dailyHours : hours) {
totalHours += dailyHours;
}
 
Back
Top