The method does not print the last odd value in the array. I tried array.size() - 1, but to no avail. What am I doing wrong?
import java.util.ArrayList;
public class Odds
{
public static void main(String[] args)
{
ArrayList<Integer> odds = new ArrayList<Integer>();
for(int index = 1; index <101; index++)
{
odds.add(index);
removeEvens(odds);
}
//call removeEvens on the array above!
}
public static void removeEvens(ArrayList<Integer> array)
{
for(int i = 0; i < array.size(); i++)
{
if (array.get(i)%2 == 0)
{
array.remove(i);
i--;
System.out.println(array.get(i));
}
if(i==array.size())
{
System.out.println(array.size() - 1);
}
}
}
}
You should address the following things in your code:
removeEvens(odds)
inside the loop. Call it after the list is initialized.i
explicitly.You should do it as follows:
import java.util.ArrayList;
public class Odds {
public static void main(String[] args) {
ArrayList<Integer> odds = new ArrayList<Integer>();
for (int index = 1; index < 101; index++) {
odds.add(index);
}
removeEvens(odds);
System.out.println(odds);
}
public static void removeEvens(ArrayList<Integer> array) {
for (int i = 0; i < array.size(); i++) {
if (array.get(i) % 2 == 0) {
array.remove(i);
}
}
}
}
Output:
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99]
I tend to prefer using explicit iterators when doing this kind of modification.
List<Integer> odds = new ArrayList<>(List.of(1,2,3,4,5,6,7));
Iterator<Integer> it = odds.iterator();
while(it.hasNext()) {
if (it.next() % 2 == 0) {
it.remove();
}
}
And then there is the Streams
version which passes the odds on down the stream for collection.
odds = odds.stream().filter(a->a%2 == 1).collect(Collectors.toList());
Both results are
[1, 3, 5, 7]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.