0

I'm doing a project were I need to remove letters systematically from an ArrayList as they show up in the words that the user puts in. Then all the remaining characters are displayed and then the elimination process continues until only vowels are left.

I cant seem to get it to eliminate the characters without the program crashing.

Here's the problematic code:

public static void Mapper(){
    Scanner make = new Scanner(System.in);
        
    char Aphabets[] ={'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
    ArrayList<Character> Alpabets = new ArrayList<>();
    String word = make.nextLine();
    for (int i = 0; i < Aphabets.length; i++) {
        Alpabets. add(i,Aphabets[i]);
    }
    for (int i = 0; i < word.length(); i++) {
        Alpabets.remove(word.charAt(i));    
    }
    System.out.println(Alpabets);
}
3
  • Do you mean "remove letters"? --- Quoting Wikipedia: "An alphabet is a standardized set of basic written symbols or graphemes (called letters)", e.g. A is a letter, and R is a letter. The whole set of 26 letters is (one example of) an alphabet.
    – Andreas
    Sep 8, 2020 at 20:31
  • yes that is what i mean Sep 8, 2020 at 20:34
  • Then you should edit the question and clarify your meaning.
    – Andreas
    Sep 8, 2020 at 21:23

2 Answers 2

0

Change

Alpabets.remove(word.charAt(i));

to

Alpabets.remove((Object) word.charAt(i));

The issue is that List.remove has two implementations (it's an overloaded method):

  • One implementation that takes an index as argument: List.remove(int index) ("remove the 5th element from the list")

  • One that removes an actual object from the list List.remove(Object o) ("remove the number 5 from the list).

By calling using Alpabets.remove(word.charAt(i)); you're accidentally invoking the one that takes an index, and if you give it a "large enough" character (characters can be seen as numerical values in Java), you'll hit an index out of bounds in the remove method.

By casting the argument to Object, you force the correct method to be called.

0

Might you can also use map key and value and remove based on user input.

2
  • Welcome to Stack Overflow! Please phrase this as an explained conditional answer, in order to avoid the impression of asking a clarification question instead of answering (for which a comment should be used instead of an answer, compare meta.stackexchange.com/questions/214173/… ). For example like "If your problem is ... then the solution is to .... because .... ."
    – Yunnosch
    Aug 29, 2021 at 17:42
  • Please add further details to expand on your answer, such as working code or documentation citations.
    – Community Bot
    Aug 30, 2021 at 4:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.