-1
I am running a loop that should iterate 30 times that corresponds to the days of the month... and this loop is iterated with data coming from the database that brings the days of registered items (example: day 6 rubber purchase), only during these days there may be no shopping and I’m wanting to fill as 0, the days there are no shopping, I’m doing as follows:
List<ProducaoDiaria> producaoDiariaDTO = producaoDiariaSS.getDados(query);
for (int i = 0; i < 30; i++) {
ProdDiaria prodDiaria = new ProdDiaria();
if (producaoDiariaDTO.get(i) != null && !producaoDiariaDTO.get(i).equals("")) {
if (producaoDiariaDTO.get(i).getDia() == i) {
prodDiaria.setCdConvenio(Integer.toString(producaoDiariaDTO.get(i).getCdConvenio()));
prodDiaria.setDia(Integer.toString(producaoDiariaDTO.get(i).getDia()));
prodDiaria.setNmConvenio(producaoDiariaDTO.get(i).getNmConvenio());
prodDiaria.setValor(producaoDiariaDTO.get(i).getValor().toString());
}
} else {
prodDiaria.setCdConvenio("");
prodDiaria.setDia(Integer.toString(i + 1));
prodDiaria.setNmConvenio("");
prodDiaria.setValor("");
}
}
But since there is only one element right after the first iteration it returns to me
java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
The expected result is:
Day 1: 0 (N existe dado)
Day 2 : 0 (N existe dado)
Day 3 : 6
Day 4 : 0 (N existe dado)
This error is because the list has only one element. When it executes in the first iteration
i == 0
, and then it all works out for that list. However, in the second iteration (which is necessarily up to the index30
ignoring the list size), wheni == 1
, give aproducaoDiariaDTO.get(1)
give thisIndexOutOfBoundsException
.– Jefferson Quesado
@Jeffersonquesado understood why the error occurs, wanted a solution actually :/
– Ikaro Sales
On how to iterate a collection: https://answall.com/a/343925/64969 https://answall.com/a/255193/64969
– Jefferson Quesado
@Jeffersonquesado in both situations is limited to the amount of items that the Array has, and I want to have 30 or not, it execute and fill with 0 the q n has
– Ikaro Sales
The logic of this code is compromised, you assume that
producaoDiariaSS.getDados(query);
will return a list whose contents will be paired with the dates contained in the respective elements. This will not happen, you will find situations where the first element(index 0) is dated on day five, the second element(index 1) is dated on day fifteen. that stretchif (producaoDiariaDTO.get(i).getDia() == i)
reinforces the need for stuffing. The output for you is to modifyproducaoDiariaSS.getDados()
to submit a list already filled in with the missing dates.– Augusto Vasques
Either you fill the null list or use another data structure. A map is probably best for this case
– hkotsubo
Since you’re using a List, isn’t it better to foreach, and first check how many elements that list has? so you already have predictability of the number of days.
– Caio Augusto Papai