[RESOLVED] Help to sum all element of an array list that is in a method
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3

Thread: [RESOLVED] Help to sum all element of an array list that is in a method

Hybrid View

  1. #1
    Join Date
    Dec 2013
    Posts
    46

    [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.

  2. #2
    Join Date
    Dec 2013
    Posts
    14

    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.

  3. #3
    Join Date
    Dec 2013
    Posts
    46

    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
  •  


Azure Activities Information Page

Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center