0

This code is to get the occurrence of the characters in the Arraylist firlast but charAt can't be used and gives an error

The method charAt(int) is undefined for the type ArrayList<String>Java(67108964)

int len = firlast.size();
                int count[] = new int[256];

                for(int i = 0; i < len; i++)
                    count[firlast.charAt(i)]++;
                
                char ch[] = new char[firlast.size()];
                for (int i = 0; i < len; i++) {
                    ch[i] = firlast.charAt(i);
                    int find = 0;
                    for (int j = 0; j < i; j++) {
                        if (firlast.charAt(i) == ch[j])
                            find++;
                    }

                    if (find == 1)
                        System.out.println("occurence " + firstlast.charAt(i) + count[firstlast.charAt(i)]);
                }

Output of the firlast array is [rj, yf, rC, ac, ps, ni, er, et, FT, ei]

I dont know what i did wrong. please point out where i did wrong.

2
  • 2
    If firlast is an ArrayList as stated in the introduction, then firlast.charAt(i) won't compile. Are you sure that this is the exact code you are executing? - If not, please refer to 'How to create a minimal reproducible example?'. Commented Aug 30, 2021 at 9:29
  • Yes this is the code. i wrote this code in a text file and compile in the cmd. just to try without intellisense. now i tried it with the VS code and now this The method charAt(int) is undefined for the type ArrayList<String>Java(67108964) Commented Aug 30, 2021 at 9:35

1 Answer 1

2

There is no charAt method on an ArrayList. The closest is List.get(int) which returns the list element at a given position.

However, in your example you have an ArrayList<String>, so get will return a String rather than a character, and you can't use a string as an array index.

Unfortunately, I think the real problem here is that ArrayList<String> is the wrong data structure for this code. Better alternatives might be char[], ArrayList<Character> String or StringBuilder. It is hard to say without more context.

Sign up to request clarification or add additional context in comments.

1 Comment

I changed arraylist to char[] and now it works i get the desired output thanks for clarification @Stephen

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.