0

So I´m writting this Java code for college and I need to remove String elements from the ArrayList. I've used an Iterator to do it but it alaways give me this error: Exception in thread "main" java.lang.IllegalStateException

How can I solve this ?

    import java.io.FileReader;
    import java.io.IOException;
    import java.nio.file.WatchEvent;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.Scanner;

    public class EX4 {
    public static void main(String[] args) throws IOException{
        Scanner input = new Scanner(new FileReader("List.txt"));
        ArrayList<String> two = new ArrayList<>();
        ArrayList<String> s = new ArrayList<>();

        // print
        while (input.hasNext()) {
            String word = input.nextLine();
            System.out.println(word);

            // b)
            if (word.length() > 2){    
                two.add(word);
            }
            
            // c)
            String chr = String.valueOf(word.charAt(word.length() -1));
            if (chr.equals("s") || chr.equals("S")){
                s.add(word);
            }
        }

        // c)
        System.out.println("\n----------------------
                            -------------------------------\n");
        for (String word : s) {
            System.out.print(word + "\n");
        }
        

        // d)
        Iterator<String> it = two.iterator();
        while(it.hasNext()){
            String i = it.next();
            for (int c = 0; c < i.length(); c++){
                if (!Character.isLetter(c)){ 
                    it.remove(); 
                }
            }
        }
        
        
    }     
}
EliunKKy
  • 3
  • 3

3 Answers3

2

Add break statement and check

Iterator<String> it = two.iterator();
    while(it.hasNext()){
        String i = it.next();
        for (int c = 0; c < i.length(); c++){
            if (!Character.isLetter(c)){ 
                it.remove();
                break;

            }
        }
    }
YaziD
  • 57
  • 9
0

The "break" in YaziDs answer should do the trick.

But you should also check the word length in the first loop because otherwise you get an error at

String chr = String.valueOf(word.charAt(word.length() - 1));
Daniel
  • 1,494
  • 9
  • 9
-1
Character.isLetter(i.charAt(c))
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes. – Mark Rotteveel Jun 09 '22 at 10:55
  • Also, how will this "[..] remove a String element from an ArrayList?"? – Mark Rotteveel Jun 09 '22 at 10:56