-
December 20th, 2013, 05:22 AM
#1
[RESOLVED] Help to sum all element of an array list that is in a method
Once again I am back...LOL
This time I need some help to add the elements of an ArrayList that I have stored in a method.
The code looks a little like this:
Code:
public static int terms(ArrayList<Integer> arr)
{
int sum = 0;
for (int i = 0; i <= arr.size(); i++)
{
sum += arr.get(i);
return sum;
}
return sum;
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
ArrayList<Integer> childAge = new ArrayList<Integer>();
//Scanner in = new Scanner(System.in);
// User input for CU's of each class left for graduation
System.out.println("Please input the ages of your granchildren (press Q to exit): ");
int age = 0;
while(in.hasNextInt())
{
age = in.nextInt();
if (age >= 1)
{
childAge.add(age);
}
else
{
System.out.println("That is an invalid entry...try using a positive integer.");
}
}
System.out.println(childAge);
System.out.println("The total of all ages: " + terms(childAge));
}
}
Somewhere I am missing something as I get the response of :
"The age ages is: 1" in my console window.
Any help with this would be appreciated.
-
December 20th, 2013, 08:50 AM
#2
Re: Help to sum all element of an array list that is in a method
At first glance , I noticed you have 2 return statements in the method "terms". Delete the one in the loop and you should be fine.
-
December 20th, 2013, 12:08 PM
#3
Re: Help to sum all element of an array list that is in a method
Thank you.... This is what I came up with that worked.
Code:
int sum = 0;
for (int i : arr)
{
sum += i;
}
return sum;
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|