Error with receiving strings to list

51 views Asked by At

It's a program to receive n strings to list and find duplicate's count for each string and print string and number of duplicates in a map.

I get this error and i can't find the problem!

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 5, Size: 5
    at java.util.ArrayList.rangeCheck(Unknown Source)
    at java.util.ArrayList.get(Unknown Source)
    at Q1.main(Q1.java:16)

Here's the code:

import java.util.*;

public class Q1 {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        Map<String,Integer> m = new HashMap<String,Integer>();
        List<String> l = new ArrayList<String>();
        int n = sc.nextInt();
        for(int i = 1; i <= n; i++) {
            l.add(sc.nextLine());
        }
        int count=1;
        for(int i = 0; i < l.size(); count = 1) {
            for(int j = 1; i < l.size(); j++){
                if(l.get(j)==l.get(i)){
                    l.remove(j);
                    count++; 
                }
            }
            m.put(l.get(i),count);
        }
        for(int i = 0;i < l.size(); count = 1) {
            System.out.println(m.get(i));
        }
    }
}
1

There are 1 answers

0
Vivek Sadh On BEST ANSWER

You are not incrementing i :

for(int i=0;i<l.size();count=1){

Also in the code below:

`for(int j = 1; i < l.size(); j++){`

Value of i is fixed and j is getting incremented infinitely as i < l.size() (Always) which leads to IndexOutOfBoundsException.