Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 3 of 3

Thread: Searching for object variables inside a 1-D array?

  1. #1
    Member Scorks's Avatar
    Join Date
    Jan 2013
    Thanked 0 Times in 0 Posts

    Default Searching for object variables inside a 1-D array?

    Hey there!

    I've been working on a program, and I've made 10 objects of the class "CampSite". Each object has 7 different variables in it (name, postal code,number of campers in party etc...). I added these 10 objects to a 1-D array. I want to be able to add up all the number of campers that've been added into this array. How would I go about doing this?


  2. #2
    Join Date
    Jun 2013
    So. Maryland, USA
    My Mood
    Thanked 899 Times in 879 Posts

    Default Re: Searching for object variables inside a 1-D array?

    This is a great use for the enhanced for loop or some other iterator of your choice:
    for ( CampSite campsite : campsiteArray )
        // enter the search criteria and any other logic here
        // using the object 'campsite'. for example, if you want
        // to find the objects with 5 campers, find those where
        // campsite.numberOfCampers == 5
    Good luck!

  3. #3
    Join Date
    Jul 2013
    Thanked 18 Times in 17 Posts

    Default Re: Searching for object variables inside a 1-D array?

    Take a variable say sum initialized to zero.
    Iterate through every object in the array. In every iteration add the number of campers to the variable sum.
    After iterating is complete, sum contains what you want.


Similar Threads

  1. Delete data from inside the object
    By ankityadav in forum What's Wrong With My Code?
    Replies: 13
    Last Post: September 5th, 2013, 09:11
  2. help Student ID searching [array list]
    By noobie in forum Collections and Generics
    Replies: 0
    Last Post: March 19th, 2013, 14:20
  3. Replies: 3
    Last Post: March 4th, 2013, 20:30
  4. [SOLVED] Sorting an object array using string variables from a string array
    By Shadud in forum What's Wrong With My Code?
    Replies: 0
    Last Post: November 26th, 2012, 16:50
  5. Only Constructing an Object Once (Details Inside)
    By avalanche72 in forum Object Oriented Programming
    Replies: 0
    Last Post: April 6th, 2012, 04:23

Tags for this Thread