Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return count from ArrayList

Tags:

java

arrays

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);   
      }
 }    
like image 839
TOD Avatar asked Feb 08 '23 10:02

TOD


1 Answers

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;
}
like image 105
Elliott Frisch Avatar answered Feb 11 '23 00:02

Elliott Frisch