Conor Niall

Greenhorn

Posts: 19

posted 11 months ago

Hi guys,

How could I check the values of an ArrayList<Integer> to see if any of its objects, when added to another number, adds up to a certain value? For example: I want to check when added to a Player's current running total they add up to 10 - if this is true call method A, if false call method B instead.

I think I would need to iterate through each object in the Arraylist using the contains() method, but I am having difficulties understanding where, when, and how to do the iteration.

Thanks in advance

How could I check the values of an ArrayList<Integer> to see if any of its objects, when added to another number, adds up to a certain value? For example: I want to check when added to a Player's current running total they add up to 10 - if this is true call method A, if false call method B instead.

I think I would need to iterate through each object in the Arraylist using the contains() method, but I am having difficulties understanding where, when, and how to do the iteration.

Thanks in advance

posted 11 months ago

makeMove() sounds like a good place. Have you learned about a for loop yet?

[OCA 8 book] [OCP 8 book] [Practice tests book] [Blog] [JavaRanch FAQ] [How To Ask Questions] [Book Promos]

Other Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, TOGAF part 1 and part 2

Conor Niall

Greenhorn

Posts: 19

posted 11 months ago

~~ArrayList#remove() has a form that takes an Object as its argument. This code:~~

~~...would remove the first "3" from numbers, if it exists.~~

Oops, doesn't seem to work. Not sure why.

Conor Niall wrote:

How would I retrieve the number from the numbers.contains() statement and then be able to use this number to add/remove it from a collection?

Example:

How would I accomplish this?

Oops, doesn't seem to work. Not sure why.

All things are lawful, but not all things are profitable.

Campbell Ritchie

Marshal

Posts: 56518

172

posted 11 months ago

I know I am late to the discussion, but what about putting the contents of the List into a sorted set, then iterating the set up to

*n*÷ 2 where*n*is the desired total. For each*i*found, you can see whether the set contains*n*−*i*, and then look for their locations in the original List.