Home > Back-end >  How to remove a String element from an ArrayList?
How to remove a String element from an ArrayList?

Time:06-08

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(); 
                }
            }
        }
        
        
    }     
}

CodePudding user response:

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;

            }
        }
    }

CodePudding user response:

Character.isLetter(i.charAt(c))

CodePudding user response:

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));
  •  Tags:  
  • java
  • Related