Answer the question
In order to leave comments, you need to log in
How to print all indexes of an array that match a condition?
A service has been created that determines the number of the month with the largest number of sales.
public class StatsService {
public int monthOfTopSales(long[] sales) {
long topSale = sales [0];
int month = 0;
int numTopMonth = 0;
for (long sale : sales) {
month ++;
if (topSale < sale) {
topSale = (int) sale;
numTopMonth=month;
}
}
return numTopMonth;
}
}
class StatsServiceTest {
@Test
void shouldFindTopMonth() {
StatsService service = new StatsService();
long[] sales = {8, 15, 13, 15, 17, 20, 19, 20, 7, 14, 14, 18};
long topMonth = service.monthOfTopSales(sales);
System.out.println(topMonth);
}
}
Answer the question
In order to leave comments, you need to log in
public class StatsService {
public ArrayList<Integer> monthsOfTopSales(long[] sales) {
long topSale = sales[0];
Integer month = 0;
ArrayList<Integer> topMonths = new ArrayList<Integer>();
for (long sale : sales) {
month ++;
if (topSale < sale) {
topSale = sale;
topMonths.clear();
topMonths.add(month);
} else if ( topSale == sale ) {
topMonths.add(month);
}
}
return topMonths;
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question