4

I have an ArrayList that stores an inventory of cars. I want the user to input start year and end year and return a number of cars in inventory in the year range specified. I have to use a foreach loop and get all the years to display. How can I count them? Below is what I have so far

public int howManyBetweenTheseYears(int startYear, int endYear)
{
   int totalYear = 0;
   for(Lamborghini year : inventory)
   { 
      if((year.getModelYear() >= startYear)
            && (year.getModelYear() <= endYear)) {
        totalYear = year.getModelYear();
        System.out.println(totalYear);   
      }
 }    

3 Answers 3

4

You're very close. Increment totalYear and return it. Something like,

public int howManyBetweenTheseYears(int startYear, int endYear) {
    int totalYear = 0;
    for (Lamborghini year : inventory) {
        int modelYear = year.getModelYear();
        if ((modelYear >= startYear) && (modelYear <= endYear)) {
            totalYear++;
            System.out.printf("modelYear: %d, total: %d%n", modelYear, 
                    totalYear);
        }
    }
    return totalYear;
}
Sign up to request clarification or add additional context in comments.

Comments

4

Since you want to count, you should increase totalYear by 1 for each car with a desired modelYear. I.e., change totalYear = year.getModelYear(); to

totalYear++;

BTW, if you are using Java 8, you may want to use lambdas.

Comments

0

If you are able to use Java 8 constructs, another approach you could use is streams and predicates. You can get a stream view of the ArrayList, apply a predicate to it, and then get the count:

public int howManyBetweenTheseYears(int startYear, int endYear) {
    return inventory.stream()
        .filter((Lamborghini year) -> (modelYear >= startYear) && (modelYear <= endYear))
        .count();
}

What this does is get a set of Lamborghini objects from the inventory that match your condition via the filter method, and then return the count of how many items matched.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.