java - Deleting a specific number in an ArrayList -
i running problem in code. have arraylist, , have bunch of zeros need remove. mixed in other numbers, want keep. however, when loop, skip on zeros , won't remove them. here code:
public static void main(string[] args) throws filenotfoundexception { scanner scan = new scanner(new file("input.txt")); arraylist<double> list = new arraylist<double>(); while(scan.hasnextline()){ list.add(scan.nextdouble()); } for(int i=1; i<list.size();i+=4){ if(list.get(i)<150000){ list.set(i-1,(double) 0); list.set(i,(double) 0); list.set(i+1,(double) 0); list.set(i+2,(double) 0); } } for(int i=2; i<list.size();i+=4){ if(list.get(i)>22.2){ list.set(i-2,(double) 0); list.set(i-1,(double) 0); list.set(i,(double) 0); list.set(i+1,(double) 0); } } for(int i=3; i<list.size();i+=4){ if(list.get(i)<1100){ list.set(i-3,(double) 0); list.set(i-2,(double) 0); list.set(i-1,(double) 0); list.set(i,(double) 0); } } for(int i=0;i<list.size();i++){ if(list.get(i)==0){ list.remove(i); } } system.out.println(list); } }
any appreciated!
you structurally modifying list while remove 0's. use iterator
while (iterator.hasnext()) { int elem = iterator.next(); if (elem == 0) iterator.remove(); }
hope helps. pd: can include code directly in question text using "{}" button
Comments
Post a Comment