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);
}
}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With