-1

I am relatively new to Java programming and I have a question regarding the following code. This is part of a class called IntArrayBag: the variable data is an array instance and the variable manyItems is the instance used to hold the number of items of the array. In the removeMany method, I do not understand why you are able to increment count by adding the remove(target) method. Since remove returns a boolean, is count incremented every time the remove method evaluates to true? This could very well be the case, but I cannot find any documentation on it in my textbook. Any clarification would be very appreciated.

**EDIT The removeMany method listed below is an answer provided by my textbook. The question was to create a method that can remove multiple items from the array, and removeMany is the answer provided by the textbook. It did not seem logical to me, which is why I am asking for clarification. Thanks in advance.

public boolean remove(int target)
{ 
    int index;
    index = 0; 
    while ((index < manyItems) && (target != data[index])) 
        index++; 
        if (index == manyItems)
            return false; 
        else { 
            manyItems--; 
            data[index] = data[manyItems]; return true; } 
}

public int removeMany(int... targets) 
{ 
    int count = 0; 
    for (int target : targets) 
        count += remove(target); 
    return count; 
}
meezspi
  • 1
  • 1
  • In correct java, you can't. And well, your partial input would not even compile. So; no idea what you are actually asking. So please provide a full [mcve] – GhostCat Mar 16 '17 at 20:43
  • The assignment you are confused with is indeed illegal. I consulted my `java` compiler (ver. 1.8.0_60) and it stated: `The operator += is undefined for the argument type(s) int, boolean`. – Izruo Mar 16 '17 at 20:45

1 Answers1

0

As already stated in the comments by Izruo, the assignment is illegal. I believe the logic was to increment count every time a remove was successful. However, the boolean returned by the remove method must be changed to an int first so that you can increment count with it. You may look into this post for doing that.

For example, this should work:

    public int removeMany(int... targets) 
{ 
    int count = 0; 
    for (int target : targets){
        int removeResult = (remove(target)) ? 1:
        count += removeResult; 
    }
return count; 
}
Community
  • 1
  • 1
skbrhmn
  • 1,124
  • 1
  • 14
  • 36