Search code examples
javawhile-loopintbluej

Using while loop, issue with referencing from static context


Currently I am working on an assignment within BlueJ. The question I have is simple (I hope). The method I wish to use within the while loop is "getRearWheelDrive()" which checks how many Lamborghinis within the ArrayList< Lamborghini > inventory have rear wheel drive. rearWheelDrive is a boolean variable.

Also I can not use a for-loop for this question, otherwise I would as it would be much easier. I am limited to the while loop.

The error message I receive is: "non-static method getIsRearWheelDrive() cannot be referenced from a static context" -I tried to create a static method but it didn't work either.

//

How do I check all the Lamborghini objects within the ArrayList library and then return an int value of how many total have rearWheelDrive? Also with the current code I have, would it cause the loop to finish once it got to the end of the index, or would it infinitely loop?

public int howManyAreRearWheelDrive()
{
    int indexPlace = 0;
    int number = 0;
    int i = 0;

    while(indexPlace <= inventory.size()) 
    {
        indexPlace++;
        inventory.get(i);
        i++;

        if(Lamborghini.getIsRearWheelDrive() == true) {
            number++;
        }
    }
    return number;

}

Solution

  • Without seeing the rest of the relevant classes in play here:

    while(indexPlace < inventory.size()) 
    {
        if(inventory.get(indexPlace++).getIsRearWheelDrive() == true) {
            number++;
        }
    }