**Firstly I typed this code **
List<Integer> list = new ArrayList<>();
for (int i = 1; i < 16 ; i++) {
if (i>10){
i*=2;
}
list.add(i);
}
System.out.println(list);
this code gave me // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 22]
then I asked to ChatGPT
He gave me this
List<Integer> list = new ArrayList<>();
for (int i = 1; i <= 15 ; i++) {
if (i < 11) {
list.add(i);
} else {
list.add(i * 2);
}
}
System.out.println(list);
}
and this
List<Integer> list = new ArrayList<>();
for (int i = 1; i < 16; i++) {
int value = i;
if (i > 10) {
value *= 2;
}
list.add(value);
}
System.out.println(list);
these codes worked correctly
but also I asked to ChatGPT what is the problem in my code, he couldn’s explain..
Could you please explain it to me ?
**I need to get this result **
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 22, 24, 26, 28, 30]
Gafarli Farid is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
The problem in your code is that i
is used as the loop index, not only as the value you want to put inside the list.
Suppose i = 10, at which point you double it, which makes it 20. You told the for
to loop as long as i <= 15
, which it’s not anymore. Hence your loop exited.
The two other snippets don’t have this problem because neither of them modifies i
. One puts a calculated value (i*2
) directly inside the list, the other uses a temporary variable (value
) to hold it.