Cinna Buns
Cinna Buns

Reputation: 13

Iterating an ArrayList to return a value

I am having trouble seeing the error of my work: I am creating an iterator (in my class LamborghiniCarLot) which will give the number of vehicles in my (ArrayList inventory;) which are rear-wheel-drive. the Lamborghini class has a method called getIsRearWheelDrive(). But attempting to call it, I get the method not found. "inventory" is the field variable holding the arraylist. Here is my code as it stands:

public int howManyAreRearWheelDrive()
{
    int numberRearWheel = 0;
    Iterator<Lamborghini> it = inventory.iterator();
    Lamborghini inv = null;

    while(it.hasNext())
    {
        inv = it.next();
        if(inv != null)
        {
            if(it.getIsRearWheelDrive() == true)
            {
                numberRearWheel ++;
            }
        }
    }
    return numberRearWheel;
}

Upvotes: 0

Views: 102

Answers (3)

Tesseract
Tesseract

Reputation: 8139

I would use a for loop

for(Lamborghini inv: inventory) {
  if(inv.getIsRearWheelDrive()) numberRearWheel++;
}

or a Stream

public int howManyAreRearWheelDrive() {
  return (int)inventory.stream().filter(inv -> inv.getIsRearWheelDrive()).count();
}

Upvotes: 0

AlecR
AlecR

Reputation: 57

Instead of it.getIsRearWheelDrive() you need to use inv.getIsRearWheelDrive() since your Lamborghini class has the method. it is your iterator and an iterator does not have a getIsRearWhileDrive() method.

Upvotes: 0

Kon
Kon

Reputation: 10810

if(it.getIsRearWheelDrive() == true)

should be

if(inv.getIsRearWheelDrive() == true)

Upvotes: 2

Related Questions