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));
}
}
}
You are not incrementing
i
:Also in the code below:
Value of i is fixed and j is getting incremented infinitely as
i < l.size()
(Always) which leads to IndexOutOfBoundsException.