Reputation: 79
How do I remove items from the arraylist I know have. I know about the remove() method, but it doesn't seem to work;
ArrayList <String> namen = new ArrayList <> ();
System.out.print("Voer een naam in:");
Scanner in = new Scanner (System.in);
for (int i = 0; i<10; i++){
namen.add(in.next());
int aantalNamen = namen.size();
System.out.println(namen);
System.out.println(aantalNamen);
if(i == 10){
namen.remove(9);
}
}
How can I change this code to make it work?
Upvotes: 0
Views: 93
Reputation: 21981
How can I change this code to make it work?
To work, you need to compare i==9
, at if
statement.
if(i == 9){
namen.remove(9);
}
Upvotes: 0
Reputation: 3115
if(i == 10){
namen.remove(9);
}
this code not work inside the loop. because when i get 10 the loop will terminate. so you put remove code in outside the loop. like this
for (int i = 0; i<10; i++){
namen.add(in.next());
int aantalNamen = namen.size();
System.out.println(namen);
System.out.println(aantalNamen);
}
namen.remove(9);
Upvotes: 0
Reputation: 45090
Because of the condition i < 10
in the for
loop, the if
in the for
will never satisfy. The for
will terminate once i
becomes 10
and therefore, the condition if(i == 10){
will never be true. That's why nothing is getting removed from your list.
You either need to change the condition of the if
to i==9
or change the condition in the for to i <= 10
.
Upvotes: 2