I was trying to delete all multiples of a chosen number from a linked list, like for example, removing multiples of 2:
[0, 12, 16, 0, 13, 9, 13, 17, 5, 12, 1, 12, 5, 5, 1, 6, 14, 12, 14, 14] -> [13, 9, 13, 17, 5, 1, 5, 5, 1]
I wrote this code to construct a linked list of 20 random integers and then, depending on the condition, remove elements from it.
import java.util.Scanner;
import java.util.*;
public class MyList {
public static void main(String args[])
{
int entero = 0;
Random random = new Random();
LinkedList<Integer> objectList = new LinkedList<Integer>();
Scanner scan = new Scanner(System.in);
for(int i=0; i<20; i++){
int randomInteger = random.nextInt(20);
objectList.add(randomInteger);
}
System.out.print("Enter a number between 1 y 5: ");
int intNumber = scan.nextInt();
if(intNumber > 5 || intNumber < 1){
}else{
System.out.println("List : " + objectList);
if(intNumber == 2){
for(int j=0; objectList.size()>j; j++){
System.out.println("va " + objectList.get(j));
if (objectList.get(j) % 2 == 0) {
objectList.remove(objectList.get(j));;
}
}
}
}
System.out.println("Final List : " + objectList);
}
}
Problem with this is that it wont delete certain items, even though it should (e.g: condition 14%2==0 gets evaluated as true, but the number wont be removed), so the result ends up like this:
from [0, 12, 16, 0, 13, 9, 13, 17, 5, 12, 1, 12, 5, 5, 1, 6, 14, 12, 14, 14] -> to [0, 13, 9, 13, 17, 5, 1, 5, 5, 1, 12, 14, 14]
Why is this not deleting all the multiples of 2 from the list?
Aucun commentaire:
Enregistrer un commentaire